jquery如何在悬停时仅更改一个父级如何在、jquery

2023-09-07 23:33:46 作者:攻你心i

当我将鼠标悬停在 <p> 标记上时,我只想更改一个父级.代码是:

I would like to change only one parent when I hover over <p> tags. The code is:

$('.hover').each(function () {
    $(this).parent().hover(function () {
            $('p').parent(this).css('font-size','30px');
        }, function () {
            $('p').parent(this).css('font-size','10px');
    });
});

HTML 是:

   <ul>
        <li>1 <p class='hover'>xxxx</p></li>
        <li>2 <p class='hover'>yyyy</p></li>
    </ul>

当我将鼠标悬停在xxxx"上时,我希望1"和xxxx"发生变化,但2"和yyyy"什么也不做,当我将鼠标悬停在yyyy"上时,我想要2"和yyyy"" 改变,但 "1" 和 "xxxx" 什么都不做.

When I hover over "xxxx", I want "1" and "xxxx" to change but "2" and "yyyy" do nothing, and when I hover over "yyyy", I want "2" and "yyyy" to change but "1" and "xxxx" do nothing.

我是 jQuery 新手.

I'm new to jQuery.

推荐答案

$('p.hover').parent().hover(function() {
    $(this).children('p').css('font-size','30px');
}, function () {
    $(this).children('p').css('font-size','10px');
});

您不必使用 each 循环来添加悬停.如果您选择了多个元素,它会将事件应用于所有元素.

You don't have to use an each loop to add the hovers. If you have multiple elements selected, it will apply the event on all elements.

话虽如此,我稍微优化了你的代码.

Having that said, I slightly optimised your code.

我已经在段落的父级上添加了悬停,就像你做的那样.通过在事件的回调中使用 $(this),我实际上可以选择悬停的元素并在该元素上应用样式.

I have added the hover on the paragraph's parent, just like you did. By using $(this) in the event's callback I can actually select the hovered element and apply styles on that element.

因为我希望字体大小应用于段落,所以我先选择所需的子项.

Because I want the font-size to apply on the paragraph, I select the desired child first.

总结起来:

查找段落元素 ($('p.hover'))获取它的父元素,li 元素 (.parent())应用悬停事件 (.hover()) Find the paragraphs elements ($('p.hover')) Get it's parent, the li element (.parent()) Apply the hover event (.hover())

调用悬停事件后:

获取当前元素($(this))查找内段(.children('p'))应用样式