【问题标题】:Repositioning a div in window if it overlaps如果重叠,则在窗口中重新定位 div
【发布时间】:2015-05-02 00:58:02
【问题描述】:

我正在使用 jQuery 在我的页面上动态创建 div。如果鼠标点击位置在屏幕下方,则 div 将部分显示在屏幕外。基本上取屏幕 680px,鼠标点击 600px,div 高度 300,由于溢出属性设置为隐藏,div 的下 220px 将超出屏幕。

我想要实现的是一个函数,它将计算向上移动多少以确保 div 完全可见。

不幸的是,它不起作用。任何帮助表示赞赏,甚至是通过 CSS 或其他方式提供的替代解决方案。

此函数应返回值top,单位为 px。基本上它应该计算 div 超出屏幕高度的高度,并将其从当前鼠标位置移除以使 div 适合。

Javascript:

var mousex;
var mousey;
var currshowingid;
var mousepos;

$( document ).on( "mousemove", function( event ) {
    mousex = event.pageX;
    mousey = event.pageY;
    //console.log( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});

function xfromtop(el) {
    if ((mousey + $(el).height()) > $(window).height()) {
        fromtop = mousey - ((mousey + $(el).height()) - $(window).height())*1.1;
        fromtop = fromtop.toString() + "px";
    } else {
        fromtop = mousey.toString() + "px";
    }
    return fromtop;
}

这将创建 div 运行时并将 xfromtop() 用于top CSS 属性

function showdriverdetails(id) {
    $('div[id^="driver_"]').remove();
    // Add div and place in at mouse position 
    $("#main").append("<div class='driverdetails dets' id='driver_" + id + "'>");
    $("#driver_" + id).load("ajax/driver_info.php?id=" + id).fadeIn().draggable();
    $("#driver_" + id).css("top", xfromtop($("#driver_" + id)));
}

CSS:

div.driverdetails {
    width: 70%;
    height: auto;
    min-height: 300px;
    max-height: 400px;
    left: 18%;
}

.dets {
    z-index: 1000;
    position: fixed;
    padding: 2px;
    border: solid #5c6cb0 2.5px;
    background-color: white;
    border-radius: 12px;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    display: none;
}

HTML:

<button onclick="showdriverdetails(100)">SHOW</button>

【问题讨论】:

  • 你能指定什么不工作吗?
  • 基本上,top 值的计算方式不正确。根据 xfromtop() 功能,每当 div 太低时,它应该将其恢复。
  • 你试过直接获取 'window.innerHeight' 而不是 jQuery hight() 吗?

标签: javascript jquery css positioning


【解决方案1】:

height 属性不考虑边距、内边距和边框。您应该使用 jQuery 的 outerHeight 来获取 div 的完整高度。

function xfromtop(el) {
    var elHeight = $(el).outerHeight();
    var windowHeight = $(window).height();

    if ((mousey + elHeight) > windowHeight) {
        fromtop = windowHeight - elHeight;
        fromtop = fromtop.toString() + "px";
    } else {
        fromtop = mousey.toString() + "px";
    }
    return fromtop;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-18
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多