Javascript 当您将鼠标悬停在.container上时,它会更改两者的颜色。但我只想改变鼠标所在的容器
我准备了这个: 当您将鼠标悬停在.container上时,它会更改两者的颜色。但我只想改变鼠标所在的容器 以下是js代码:Javascript 当您将鼠标悬停在.container上时,它会更改两者的颜色。但我只想改变鼠标所在的容器,javascript,jquery,html,css-selectors,Javascript,Jquery,Html,Css Selectors,我准备了这个: 当您将鼠标悬停在.container上时,它会更改两者的颜色。但我只想改变鼠标所在的容器 以下是js代码: moped = ""; $(".container").mouseenter(function () { $(".content").css('background', function () { moped = $(this).css('background'); return "green"; });}).mousele
moped = "";
$(".container").mouseenter(function () {
$(".content").css('background', function () {
moped = $(this).css('background');
return "green";
});}).mouseleave(function () {
$(".content").css('background', function () {
return moped;
});
});
html:
将
$(“.content”)
更改为$(this)。在.mouseenter
函数中查找(“.content”)
,它将只更改您悬停在上面的一个。您可以将其更改为$(“.content”,this)
,但根据评论中的epascarello,它没有那么有效。其他答案显示了jQuery代码中的错误,但另一个修复方法是仅使用CSS
给外部元素一个公共类,然后:
.cont {
background:red;
}
.cont:hover .content {
background: green;
}
演示:
但是对于jQuery代码,不仅需要查找嵌套的
.content
,而且不需要变量。只需在mouseleave
中将背景设置为”
$(".container").mouseenter(function () {
$(this).find(".content").css('background', "green");
}).mouseleave(function () {
$(this).find(".content").css('background', "");
});
您可以移动css背景属性,也可以执行以下操作:
moped = "";
$(".container").mouseenter(function () {
$(this).children(".content").css('background', function () {
moped = $(this).css('background-color');
return "green";
});
}).mouseleave(function () {
$(this).children(".content").css('background', function () {
return moped;
});
});
我的建议是使用脚本并对其进行重构,使用.hover()
并分别命名mouseenter
和mouseout
函数。
祝你好运,伙计。上下文选择器性能很差,最好使用
$(这个)。查找(“.content”)
@epascarello哦,我不知道。谢谢你,我会按照建议的用途更新答案。这就是我要找的。谢谢这就是解决方案:我刚刚做了一个基准测试,Chrome 28的差异约为6%。不是很大,但也不是可以忽略的@Barmar我喜欢了解性能方面的事情,所以这肯定是我将来会记住的事情。在你完成了两段代码之后,再从你的小提琴上复制一段代码会不会让你丧命?
$(".container").mouseenter(function () {
$(this).find(".content").css('background', "green");
}).mouseleave(function () {
$(this).find(".content").css('background', "");
});
moped = "";
$(".container").mouseenter(function () {
$(this).children(".content").css('background', function () {
moped = $(this).css('background-color');
return "green";
});
}).mouseleave(function () {
$(this).children(".content").css('background', function () {
return moped;
});
});