繁体   English   中英

jQuery:如何添加div覆盖鼠标悬停的元素?

[英]jQuery: How can I add a div to cover the element the mouse over?

我想添加一个div来覆盖鼠标在网页中悬停的元素。 我尝试如下,但失败了。 我该怎么做? 谢谢!

  jQuery(function ($) {

    $("*").bind("mouseenter.noteEvent", function (event) {

    var offset = $(this).offset();
    var enterBg = "<div id = 'tooltip_enterbg'></div>";
    $("body").append(enterBg);
    $("#tooltip_enterbg")
        .css({
                "top": offset.top + "px",
                "left": offset.left + "px",
                "width": $(this).width(),
                "height": $(this).height(),
                "opacity": 0.5,
                "background-color": "#FFFF00"}
        );

    });

    $("*").bind("mouseleave.noteEvent", function (event) {
       $("#tooltip_enterbg").remove();
    });

});

jsfiddle演示:在此演示中,当鼠标移至“ AAA”时,整个页面变为浅黄色 ,我只希望“ AAA”变为浅黄色。

您缺少的是position: absolute ,例如:

$("#tooltip_enterbg")
    .css({
            "top": offset.top + "px",
            "left": offset.left + "px",
            "width": $(this).width(),
            "height": $(this).height(),
            "opacity": 0.5,
            "background-color": "#FFFF00",
            "position": "absolute"}     // <===== Here
    );

边注:

无需查找刚刚添加的元素。 更改

var enterBg = "<div id = 'tooltip_enterbg'></div>";
$("body").append(enterBg);
$("#tooltip_enterbg")
    .css/*...*/

var enterBg = $("<div id = 'tooltip_enterbg'></div>");
$("body").append(enterBg);
enterBg
    .css/*...*/

使用以下代码:

jQuery(function ($) {

    $("p").bind("mouseenter.noteEvent", function (event) {

    var offset = $(this).offset();
    var enterBg = "<div id = 'tooltip_enterbg'></div>";
    $("body").append(enterBg);
    $("#tooltip_enterbg")
        .css({
                "top": offset.top + "px",
                "left": offset.left + "px",
                "width": $(this).width(),
                "height": $(this).height(),
                "opacity": 0.5,
                "background-color": "#FFFF00",
                "position": "fixed"}
        );
    });

    $("p").bind("mouseleave.noteEvent", function (event) {
       $("#tooltip_enterbg").remove();
    });
});

该演示在这里: http : //jsfiddle.net/Mv472/3/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM