我试图创建一个脚本,用于在图像悬停时更改文本。这是简单版本的HTML:
<section id="#first">
<div class="img-1"></div>
<div class="img-2"></div>
</section>
<section id="#second">
<div class="text-1"></div>
<div class="text-2"></div>
</section>Javascript
jQuery(document).ready(function($){
$('.img-1').hover(
function(){ $('.text-1').addClass('text-1-active') },
function(){ $('.img-1').addClass('img-1-active') },
function(){ $('.text-2').removeClass('text-2-active') },
function(){ $('.img-2').removeClass('img-2-active') }
)
$('.img-2').hover(
function(){ $('.text-2').addClass('text-2-active') },
function(){ $('.img-2').addClass('img-2-active') },
function(){ $('.img-1').removeClass('img-1-active') },
function(){ $('.text-1').removeClass('text-1-active') }
)});
无法更改HTML结构。类确实会被添加,但不会被删除。
小提琴
发布于 2014-09-05 17:43:23
)实际上,这就是您所需要的:演示
$("#first [class^=img-]").hover(function() {
$('#second .text-'+ this.className.replace(/\D/g,'')).toggle();
});如果你想切换类的话?没有比这更简单的了:演示
$("#first [class^=img-]").hover(function() {
$(this).toggleClass("wow");
$('#second .text-'+ this.className.replace(/\D/g,'')).toggleClass("wow");
});为了解释上面的内容,您只需要找出悬停元素的数量和所需的.text-N元素的引用号。
同样是这个<section id="#first">,#first是,而不是将ID设置为HTML元素的方式。
使用简单的<section id="first">
发布于 2014-09-05 17:28:01
您正在尝试传递四个单独的回调函数,而不是执行所有必要代码的单个回调函数。
这是你想要的:
jQuery(document).ready(function($){
$('.img-1').hover(
function(){
$('.text-1').addClass('text-1-active');
$('.img-1').addClass('img-1-active');
$('.text-2').removeClass('text-2-active');
$('.img-2').removeClass('img-2-active');
}
)
$('.img-2').hover(
function(){
$('.text-2').addClass('text-2-active');
$('.img-2').addClass('img-2-active');
$('.img-1').removeClass('img-1-active');
$('.text-1').removeClass('text-1-active');
}
)
});http://jsfiddle.net/w4mLtec8/5/
发布于 2014-09-05 17:29:25
您正在向hover事件传递一个函数列表。把它寄给我就行了。
也就是。
jQuery(document).ready(function($) {
$('.img-1').hover(
function() {
$('.text-1').addClass('text-1-active');
$('.img-1').addClass('img-1-active');
$('.text-2').removeClass('text-2-active');
$('.img-2').removeClass('img-2-active');
}
);
$('.img-2').hover(
function() {
$('.text-2').addClass('text-2-active');
$('.img-2').addClass('img-2-active');
$('.img-1').removeClass('img-1-active');
$('.text-1').removeClass('text-1-active');
}
);
});https://stackoverflow.com/questions/25690977
复制相似问题