找到没有孩子的元素

时间:2014-06-23 20:17:50

标签: jquery html dom jquery-selectors

我的目标:在悬停元素时更改元素的背景。

问题:我有一个*选择器,可以为所有元素添加mouseover/mouseout效果。 但是,我只需要改变我悬停的最深元素的背景,即没有子元素的元素。

HTML:

<body>
    <div id="skinke" niveau="1">
        <img niveau="2" class="hest" id="dyr" src="http://upload.wikimedia.org/wikipedia/commons/d/db/Patern_test.jpg" />
    </div>
    <div class="bil hest" niveau="1">
        <p niveau="2">Asdnjkewr</p>
    </div>
    <ul niveau="1">
        <li class="aefae" niveau="2">
            <p id="bold" niveau="3">1. sdfsdf</p>
        </li>
        <li niveau="2">
            <p id="to" niveau="3">fiweorew</p> <---- I want only the <p> tag to change background
        </li>
        <li>
            <p class="re">werwerw</p>
        </li>
        <li>
            <p>wreer</p>
        </li>
    </ul>
</body>

为了澄清,我在上面添加了一条评论以帮助理解。

3 个答案:

答案 0 :(得分:0)

您可以使用jQuery:

$(elementBeingHovered).hover(function() {
    $(elementToChange).css("background-color", "red");
});

或者,如果您要悬停您想要更改的同一元素:

#to:hover {
    background-color: red;
}

答案 1 :(得分:0)

我不太确定我完全抓住了你的目标和意图,但以下内容可能会有所帮助,特别是在确定任何悬停元素的最深层元素时。

方法.contents()返回所有子项,包括textNodes(nodeType = 3)。当只有textnode children时,while循环停止。

$(function() {
    $('*').hover(function() {
        var that = $(this);
        while( that.contents().filter(function() { return this.nodeType == 1; }).length > 0 ) {
            that = that.contents().filter(function() { return this.nodeType == 1; });
        };
        that.css('backgroundColor', 'red');
    });
});

JSFIDDLE DEMO

我希望这可以帮助您实现目标。

答案 2 :(得分:0)

您可以使用事件委派并将单击处理程序绑定到document,而不是将处理程序绑定到每个元素。 (这也有使用动态添加元素的附加优势。

由于<h1>,评论中提到的:empty选择器不适用于<p>textNodes等元素。您可以使用children()方法来检查实际的子元素,如下所示:

$(document).on('mouseenter','*',function(){
 if(!$(this).children().length)
   $(this).addClass('highlight');
});
$(document).on('mouseleave','*',function(){
 if($(this).hasClass('highlight'))
   $(this).removeClass('highlight');
});

CSS

.highlight{
  background-color:dodgerblue;
}

Demo

相关问题