最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Making a javascript popup draggable - Stack Overflow

programmeradmin1浏览0评论

I am creating a JavaScript popup. The code is as below.

The HTML:

    <div id="ac-wrapper" style='display:none' onClick="hideNow(event)">
    <div id="popup">
        <center>
             <h2>Popup Content Here</h2> 
            <input type="submit" name="submit" value="Submit" onClick="PopUp('hide')" />
        </center>
    </div>
</div>

The CSS:

    #ac-wrapper {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url("images/pop-bg.png") repeat top left transparent;
    z-index: 1001;
}
#popup {
    background: none repeat scroll 0 0 #FFFFFF;
    border-radius: 18px;
    -moz-border-radius: 18px;
    -webkit-border-radius: 18px;
    height: 361px;
    margin: 5% auto;
    position: relative;
    width: 597px;
}

The Script:

function PopUp(hideOrshow) {
    if (hideOrshow == 'hide') document.getElementById('ac-wrapper').style.display = "none";
    else document.getElementById('ac-wrapper').removeAttribute('style');
}
window.onload = function () {
    setTimeout(function () {
        PopUp('show');
    }, 0);
}

function hideNow(e) {
    if (e.target.id == 'ac-wrapper') document.getElementById('ac-wrapper').style.display = 'none';
}

The jsFiddle Link:

/

The Issue:

The above script works fine, but I need to make the popUp draggable.

I am creating a JavaScript popup. The code is as below.

The HTML:

    <div id="ac-wrapper" style='display:none' onClick="hideNow(event)">
    <div id="popup">
        <center>
             <h2>Popup Content Here</h2> 
            <input type="submit" name="submit" value="Submit" onClick="PopUp('hide')" />
        </center>
    </div>
</div>

The CSS:

    #ac-wrapper {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url("images/pop-bg.png") repeat top left transparent;
    z-index: 1001;
}
#popup {
    background: none repeat scroll 0 0 #FFFFFF;
    border-radius: 18px;
    -moz-border-radius: 18px;
    -webkit-border-radius: 18px;
    height: 361px;
    margin: 5% auto;
    position: relative;
    width: 597px;
}

The Script:

function PopUp(hideOrshow) {
    if (hideOrshow == 'hide') document.getElementById('ac-wrapper').style.display = "none";
    else document.getElementById('ac-wrapper').removeAttribute('style');
}
window.onload = function () {
    setTimeout(function () {
        PopUp('show');
    }, 0);
}

function hideNow(e) {
    if (e.target.id == 'ac-wrapper') document.getElementById('ac-wrapper').style.display = 'none';
}

The jsFiddle Link:

http://jsfiddle/K9qL4/2/

The Issue:

The above script works fine, but I need to make the popUp draggable.

Share asked May 19, 2014 at 12:16 NiteshNitesh 15.8k4 gold badges50 silver badges60 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Here's some code that will do what you want. It relies only on an object called drag to store all its values, but you can easily alter that. The example relies on there being a div with the id of mydiv (a document.write() is used in this instance to supply that) that has a position attribute of absolute or fixed. You can see it in action at Jamie

document.write("<" + "div id='mydiv' style='background:blue; width:100px;"
  "height:100px; position:fixed;'>" + "<" + "/div>");

var drag     = new Object();
drag.obj = document.getElementById('mydiv');

drag.obj.addEventListener('mousedown', function(e)
{
    drag.top  = parseInt(drag.obj.offsetTop);
    drag.left = parseInt(drag.obj.offsetLeft);
    drag.oldx = drag.x;
    drag.oldy = drag.y;
    drag.drag = true;
});

window.addEventListener('mouseup', function()
{
    drag.drag = false;
});

window.addEventListener('mousemove', function(e)
{
    drag.x    = e.clientX;
    drag.y    = e.clientY;
    var diffw = drag.x - drag.oldx;
    var diffh = drag.y - drag.oldy;

    if (drag.drag)
    {
        drag.obj.style.left = drag.left + diffw + 'px';
        drag.obj.style.top  = drag.top  + diffh + 'px';
        e.preventDefault();
    }
});

Use the

.draggable();

jquery function, here is your updated fiddle:

http://jsfiddle/N9rQK/

If you don't want to use jQuery, you should read this subject: Draggable div without jQuery UI

Since there is no solution that handles the popup window draggable exactly as OP asked, here is one. The closes solution available here adds a new element to the OP's document which is dragable, not the popup.

Features:

  • Uses the document's mousemove event to re-position the popup.
  • Prevents the popup from leaving the document boundary.
  • Prevent the mousedown events to propagate from child input elements.

Code:

let dragPopup = false;
let mouseX = 0;
let mouseY = 0;

function PopUp(hideOrshow) {
  if (hideOrshow == 'hide') {
    document.getElementById('ac-wrapper').style.display = "none";
  } else {
    document.getElementById('ac-wrapper').removeAttribute('style');

    // Placing the popup in the center middle of the screen;
    const popup = document.getElementById("popup");
    popup.style.top = `${(document.documentElement.scrollHeight / 2) - (popup.offsetHeight / 2)}px`
    popup.style.left = `${(document.documentElement.scrollWidth / 2) - (popup.offsetWidth / 2)}px`
  }
}
window.onload = function() {
  setTimeout(function() {
    PopUp('show');
  }, 0);

  const popup = document.getElementById("popup");

  popup.onmousedown = (e) => {
    dragPopup = true;
    mouseX = e.pageX - popup.offsetLeft;
    mouseY = e.pageY - popup.offsetTop;
    popup.classList.add("drag");
  }

  popup.onmouseup = () => {
    dragPopup = false;
    popup.classList.remove("drag");
  }

  document.onmouseup = () => {
    dragPopup = false;
    popup.classList.remove("drag");
  }

  document.onmousemove = (e) => {
    if (dragPopup) {
      if (e.pageX - mouseX + popup.offsetWidth > document.documentElement.scrollWidth) {
        popup.style.left = `${document.documentElement.scrollWidth - popup.offsetWidth}px`;
      } else if (e.pageX - mouseX >= 0) {
        popup.style.left = `${e.pageX - mouseX}px`;
      } else {
        popup.style.left = `${0}px`;
      }
      
      if (e.pageY - mouseY + popup.offsetHeight > document.documentElement.scrollHeight) {
        popup.style.top = `${document.documentElement.scrollHeight - popup.offsetHeight}px`;
      } else if (e.pageY - mouseY > 0) {
        popup.style.top = `${e.pageY - mouseY}px`;
      } else {
        popup.style.top = `${0}px`;
      }
    }
  }
  
  // Disabling mousedown event to propogate from input child elements to avoid unnecessary drags.
  for (const child of popup.getElementsByTagName("center")[0].children) {
    // Except if child is h2 element
    if (child.tagName === "INPUT") child.onmousedown = (e) => e.stopPropagation();
  }
}

function hideNow(e) {
  if (e.target.id == 'ac-wrapper') document.getElementById('ac-wrapper').style.display = 'none';
}
body, html {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

#ac-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  width: cacl(100% - 40px);
  height: calc(100% - 40px);
  background: url("https://media.istockphoto./id/1248762159/video/pop-up-circle-animation-background.jpg?s=640x640&k=20&c=4jogwiqXww2UG7s4N5W-Us-AS4QJqqTcKMCenCtztvA=") 0% / 100% 100% transparent no-repeat scroll border-box;
  z-index: 1001;
  padding: 20px;
}

#popup {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 18px;
  -moz-border-radius: 18px;
  -webkit-border-radius: 18px;
  height: 100px;
  width: 500px;
  
  /* Changing position to absolute to make it dragable */
  position: absolute;
  backdrop-filter: blur(3px);
}

#popup.drag {
  cursor: move;
}

#popup h2 {
  user-select: none;
}
<div id="ac-wrapper" style='display:none' onClick="hideNow(event)">
  <div id="popup">
    <center>
      <h2>Popup Content Here</h2>
      <input type="submit" name="submit" value="Submit" onClick="PopUp('hide')" />
    </center>
  </div>
</div>

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>