我制作了一些菜单,其中的元素会在用户点击它们时展开。每当菜单项展开时,元素的标题应该使用 .css() 更改样式
由于菜单的样式不同,因此脚本中有一个 if 语句,用于检查用户是否单击了 menu2 或 menu3 项以在展开时应用适当的样式。
编辑:问题是样式更改没有按应有的方式应用。
我按照 Sushanth 的建议将 $this 替换为 $(this),但问题仍然存在,请检查示例(已更新)
代码:
<script type='text/javascript'>
$(window).load(function(){
$(document).ready(function() {
$(".toggle-trigger").click(function() {
$(this).parent().nextAll('.toggle-wrap').first().slideToggle('slow','swing');
if( $(this).is("menu2 .headline a")) {
$(this).toggle(
function(){
$(this).parent().css("background-color","rgba(0, 0, 0, 0.1)",'border', 'solid 2px #009e0f');
$(this).css("color","#009e0f");
},
function(){
$(this).parent().css("background-color","#009e0f","border",'solid 2px #009e0f');
$(this).css("color","#ffffff");
}
);
}
else if( $(this).is("#menu3 .headline a")) {
$(this).toggle(
function(){
$(this).parent().css("background-color","rgba(0, 0, 0, 0.1)",'border', 'solid 2px #f7b50c');
$(this).css("color","#f7b50c");
},
function(){
$(this).parent().css("background-color","#009e0f","border",'solid 2px #f7b50c');
$(this).css("color","#ffffff");
}
);
}
});
});
});
最佳答案
$this
应该是 // 在 if 语句中 if( $this.is("menu2 .headline a"))
$(this)
或者缓存 var $this = $(this)
更新
我看到代码还有两个问题......
在这一行中缺少#符号
if( $(this).is("#menu2 .headline a"))
第二个问题是您分配 CSS 属性的方式。。.css("background-color","#009e0f","border",'solid 2px #f7b50c')
您有多个属性..所以属性应该采用映射
的形式,带有键:值对..
.css({
"background-color": "#009e0f",
"border": 'solid 2px #f7b50c'
});
无需将您的代码包含在 $(window).load()
和 DOM Ready handler
中。一个就足够了。
切换
更新
优化不使用切换
$(document).ready(function() {
$(".toggle-trigger").click(function() {
// cache the div next to anchor
var $div = $(this).parent().nextAll('.toggle-wrap').first();
$div.slideToggle('slow', 'swing');
// cache $(this)
var $this = $(this);
var background = '';
var color = '';
// Checking id the div has no class called hidden
if (!$div.hasClass('hidden')) {
// then add the class to the div
$div.addClass('hidden');
background = "rgba(0, 0, 0, 0.1)";
// closest ancestor of the link cliked is menu2
if ($this.closest('#menu2').length) {
color = "#009e0f";
}
// closest ancestor of the link cliked is menu2
else if ($this.closest('#menu3').length) {
color = "#f7b50c";
}
}
// if the div has a class hidden then
else {
// Remove the hidden class
$div.removeClass('hidden');
color = "#ffffff";
if ($this.closest('#menu2').length) {
background = "#009e0f";
}
else if ($this.closest('#menu3').length) {
background = "#f7b50c";
}
}
// set the background and color based on conditions
$this.parent().css("background-color" , background );
$this.css("color" , color);
});
});
关于jquery - 在 if 语句中使用 jQuery 更改 css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13402785/