动态更改UL样式

Dynamically changing UL style

本文关键字:样式 UL 动态      更新时间:2023-09-26

我有一个无序列表与几个"li"元素。这个想法是突出当前的"li",它当前处于焦点(悬停)。

使用如下代码

li[i].onmouseover = function() {
    this.style.backgroundColor = 'lime';
    this.style.borderLeft='5px solid red';
    this.style.listStyle = 'square';
};

Here's working fiddle

我想要一个左边框出现在悬停元素,这是发生在小提琴。但这似乎使文本向右移动。如何摆脱文本跳跃的行为?

我的下一个问题是我们可以为ul创建自己的符号吗?目前我在正方形和圆盘之间切换。有可能在每个"里"上有花哨的图标吗?

解决方案如下。

HTML:

<h1>Introduction to the DOM</h1>
<p class="test">There are a number of reasons why the
DOM is awesome, here are some:</p>
<ul>
<li id="everywhere">It can be found everywhere.</li>
<li class="test">It's easy to use.</li>
<li class="test">It can help you to find what you want, really quickly.</li>
</ul>
JavaScript:

var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
    li[i].onmouseover = function() {
        this.style.backgroundColor = 'lime';
        this.style.borderLeft='5px solid red';
        this.style.listStyle = 'square';
    };
    li[i].onmouseout = function() {
        this.style.backgroundColor = 'white';
        this.style.borderLeft='';
        this.style.listStyle = 'disc';
    };
}
CSS:

ul li {line-height:30px; padding-left: 10px; border-left:5px solid transparent;}
#element {
    background: linear-gradient(top, black 0%, white 100%);
}

添加一个相同宽度的透明边框,当你不悬停时,也,而不是动态地改变样式,请只改变className,并保持它们属于的样式

如果你能使用伪元素:hover就更好了(除非你真的需要支持IE..啊. .)

下面的代码可以通过css技巧来实现添加到你的css

ul li {line-height:30px; padding-left: 15px; border-left:5px solid white}

它在这里工作得很好http://jsfiddle.net/sarfarazdesigner/XNqaV/2/