首页 > 解决方案 > 在悬停时定位 div 时出现问题

问题描述

我希望能够在悬停文本框时在另一个下方显示一个 div。到目前为止,我的方法是这样的:

CSS:

.place-info {
    position: absolute;
    top: 0;
    left: 0;
    color: rgba(0,0,0,0.8);
    background-color: white;
    border-radius: 200px;
    -webkit-animation: fadeIn 500ms;
}

.live_results {
    position: relative;
    max-width: 100%;
    min-height: 200px;
    margin-right: 10px;
}

place_info 是悬停时显示的元素的类,live_results 是 div 相对的容器。

我正在使用以下代码创建 place_info:

JS:

$(document).on('mouseenter', ".station-code", function () {
    var code = this.textContent;
    var places = myResponse[0][0]['Places'];
    var place_info = getPlaceInfo(code, places);
    if (place_info == null) {
        places = myResponse[0][1]['Places'];
        place_info = getPlaceInfo(code, places);
    }
    createDivPlaceInfo(this, place_info);
});

$(document).on('mouseleave', '.station-code', function () {
    var place_info = document.getElementsByClassName('place-info');
    for (var i = 0; i < place_info.length; i++) {
        place_info[i].parentNode.removeChild(place_info[i]);
    }
});

function createDivPlaceInfo(elem, place_info) {
    var body = document.getElementById('live_results');
    var div = document.createElement('div');
    div.className = "place-info p-3";
    div.id = "place-info";
    div.appendChild(document.createTextNode(
        place_info['Name'] + ', ' + place_info['ParentName']
    ));

    var rect = elem.getBoundingClientRect();
    console.log([rect.x, rect.y]);
    var coord = [rect.x + 10, rect.y + 10];

    div.style.transform = "translate(" + coord[0] + "px, " + coord[1] + "px)";
    body.appendChild(div);
}

使用此代码,我成功显示了 div,但定位从来都不是恒定的,我注意到它取决于我向下滚动页面的距离。为了更好地了解我想要做什么,请尝试将机场代码悬停在 Skyscanner 页面上。 https://www.skyscanner.net/transport/flights/olb/zuri/190816/190823?flexible_origin=true&flexible_depart=direct&flexible_return=direct&adults=1&children=0&adultsv2=1&childrenv2=&infants=0&cabinclass=economy&rtn=1&preferdirects=false&falseboundaltsenabled=false&inboundaltsenabled=结果

标签: javascriptcssposition

解决方案


var body = document.getElementById('live_results');
body.appendChild(div);
.live_results {
    position: relative;
    max-width: 100%;
    min-height: 200px;
    margin-right: 10px;
}

我从您的代码中可以看到,您正在使用 .live_results 来设置样式,而在您的方法中,您正在使用 document.getElementById 选择父级,这可能是您的样式从一开始就没有得到应用并且相对定位的原因记录而不是父 div。


推荐阅读