1

我有一个简单的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.
        }
    }

滑块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>

正是我想要的是在鼠标悬停时删除两者的样式。

任何帮助表示赞赏。

4

2 回答 2

3

指定0px

pOld.style.width='0px';
于 2013-06-29T12:27:49.487 回答
2

一个非常好的解决方案是使用类。添加和删​​除类,而不是添加样式。以下代码将一个类添加到要设置样式的组件中。

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 在 raw 中完成(也许如果您只需要执行一个简单的操作),但在一般情况下,jQuery 是要走的路。

实施后,将其添加到您的项目中:

<script>
$( document ).ready(function() {
//$("here goes the ID, class, component w.e. you desire")
    $(".widthAlteration").click(function(){
        $(this).removeClass(".widthAlteration");
    });
});
</script>
于 2013-06-29T12:39:36.077 回答