0

I am trying to add border only to the element where my mouse is, but my code is add border to its parent element as well,

My code:

jQuery('body').mousemove(function(e){   
var el = e.target;
        jQuery(el).hover(function(){
            jQuery(this).css('outline','solid 2px #000');
        },function(){
            jQuery(this).css('outline','');
        });
});

Fiddle here: http://jsfiddle.net/howtoplease/gk8t7/

4

5 回答 5

5

主要问题是使用.hover.hover使用事件mouseentermouseleave. mouseleave当您输入子元素时不会在父元素上触发,因此大纲将一直保留到您“离开”父元素和所有子元素。此外,您需要防止mouseover子代上的 a 传播给父代。

//jQuery('body').mousemove(function(e){ 
    //var el = e.target;
    jQuery('div').mouseover(function (e) {
        e.stopPropagation();
        jQuery(this).css('outline', 'solid 2px #000');
    }).mouseout(function () {
        jQuery(this).css('outline', '');
    });
//});

http://jsfiddle.net/gk8t7/9/

另外,我不太明白您为什么要使用body mousemove,这是一个调试工具,您不知道要在哪些元素上定义它吗?

于 2013-07-22T14:43:45.640 回答
2

如果您不想使用类,请使用 jQuery的parents()方法。

$('div').hover(function(e){ 
    $(this).parents().css('outline','');
    jQuery(this).css('outline','solid 2px #000');
},function(){
    $(this).parent('div').css('outline','solid 2px #000');
    jQuery(this).css('outline','');
});

如果您将鼠标移出,则实际上您已经在父元素上并且您从未将鼠标移出它,因此您会发现父 div 包装了$(this)using parent()并为其提供了边框以进行模拟。

示例:http: //jsfiddle.net/gk8t7/13/

于 2013-07-22T14:47:58.923 回答
2

你可以很简单地做到这一点。为所有元素添加一个类名(在这种情况下,我只使用“div”,因为只有 div)应该获取大纲并将以下事件侦听器添加到您的 js。

jQuery('div').mousemove(function (e) {
    $el = $(e.target)
    $('div').removeClass('outline')
    $el.addClass('outline')
});

http://jsfiddle.net/gk8t7/12/

于 2013-07-22T14:40:09.717 回答
1

利用

e.stopPropagation();

不让它影响父元素。

于 2013-07-22T14:37:11.677 回答
1

使用一个类来改变大纲,否则你永远不知道从哪里删除大纲:

jQuery('body').mousemove(function (e) {
    var el = e.target;
    $('.outline').removeClass('outline'); //remove outline
    jQuery(el).addClass('outline'); // add outline
});

CSS:

.outline {
    outline: solid 2px #000;
}

演示:http: //jsfiddle.net/maniator/UQhVE/

于 2013-07-22T14:39:55.483 回答