我有一个简单的javascript,当轮到显示时,它会向滑块添加样式,但我想在下一个滑块出现时删除样式,并在鼠标悬停时删除这两种样式。
这是我的javascript函数,它将style="width:200px"添加到新滑块,并将style="width="200px"添加到旧滑块。
function test(){
var read = document.getElementById("slide-0") // how can i add here to read the incremented slide-0, slide-1, slide-2
.removeAttribute("style",0);
}
function noEffect(pOld,pNew){
if (pOld){
pOld.style.width='10px';
}
if (pNew){
pNew.style.width='200px'; //this style become on active slider.
}
}
Slider html
<div class="slider" onMouseOver="test()">
<ul>
<li id="slide-0" class="slide" style="width: 10px"><img src="image.jpg"></li>
<li id="slide-1" class="slide" style="width: 200px"><img src="image.jpg"></li> <!-- this is active now -->
</ul>
</div>
正是我想要的是在mouseover上删除两者的样式。
感谢您的帮助。
指定0px
pOld.style.width='0px';
一个非常好的解决方案是使用类。添加和删除类,而不是添加样式。下面的代码将一个类添加到将要设置样式的组件中。
var d = document.getElementById("div1");
d.className = d.className + " widthAlteration";
在你的CSS中有:
.widthAlteration
{
//width alteration
}
如果你想恢复效果,也可以这样做:
var d = document.getElementById("div1");
d.className = "";
或者为了方便起见,有一个集成的命令:
var ele = document.getElementById("div1");
addClass(ele, "widthAlteration");
// or
removeClass(ele, "widthALteration");
鉴于前一部分不起作用,我建议使用jQuery
在项目中实现.js文件并使用jQuery。它是最常用的库之一。很少看到JS是以原始方式完成的(也许你只需要执行一个简单的操作),但在一般情况下,jQuery是最好的选择。
实施后,将其添加到您的项目中:
<script>
$( document ).ready(function() {
//$("here goes the ID, class, component w.e. you desire")
$(".widthAlteration").click(function(){
$(this).removeClass(".widthAlteration");
});
});
</script>