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

时间:2014-03-20 07:35:42

标签: javascript jquery html

我想添加一个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 Demo:  在这个演示中,当鼠标移动到&#34; AAA&#34;时,整个页面变为淡黄色,我只想要&#34; AAA&#34;变得淡淡的黄色。

2 个答案:

答案 0 :(得分:0)

您错过的位是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/*...*/

答案 1 :(得分:0)

使用以下代码:

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/

相关问题