简体   繁体   English

Javascript切换列表样式

[英]Javascript toggle list-style

I am trying to build a little toggle switch which removes line numbers on click. 我正在尝试构建一个小的切换开关,它可以在点击时删除行号。

I have got it working here: http://www.webdevout.net/test?09&raw 我在这里工作: http//www.webdevout.net/test? 09& lt

It is code highlighted by Geshi, and i build the javascript at the top to toggle line numbers. 它是由Geshi突出显示的代码,我在顶部构建了javascript来切换行号。

This works fine, but what I would really want is that when the line numbers are 'hidden', that it also removes that gap on the left. 这样可以正常工作,但我真正想要的是当行号被“隐藏”时,它也会消除左边的间隙。 So that the actual code fills the screen. 这样实际的代码填满了屏幕。

If clicked again, the lines numbers would come back again. 如果再次单击,行号将再次返回。

You have to change the ol element's padding to 0: 您必须将ol元素的填充更改为0:

document.getElementsByTagName("ol")[0].style.padding = '0';

Above script is assuming you only have one <ol> in your document, or at least the first one is the one you'd like to edit. 上面的脚本假设您的文档中只有一个<ol> ,或者至少第一个是您要编辑的那个<ol>

EDIT 编辑

You would have to switch between 你必须在它们之间切换

document.getElementsByTagName("ol")[0].style.paddingLeft = '20px';

and

document.getElementsByTagName("ol")[0].style.paddingLeft = '0px';

Your approach is a tad bit wrong though, you should be changing the listStyle of the <ol> tag and not of the individual <li> tags. 你的方法有点不对,你应该改变<ol>标签的listStyle而不是单个<li>标签。

document.getElementsByTagName("ol")[0].style.listStyle = 'none';

and

document.getElementsByTagName("ol")[0].style.listStyle = 'decimal';

EDIT2 Perhaps give this a try. EDIT2也许试一试。 If you could also link me to it, I can test it in chrome and firefox as well. 如果您也可以将我链接到它,我也可以在chrome和firefox中测试它。 Maybe I'm not getting your problem.. 也许我没有得到你的问题..

function toggle_visibility() {
     var e = document.getElementsByTagName("ol")[0];
     if(e.style.listStyle == 'none') {
       e.style.listStyle = 'decimal';
       e.style.paddingLeft = '20px';
     } else {
       e.style.listStyle = 'none';
       e.style.paddingLeft = '0px';
     }
  }
}

Link 链接

<a onclick="toggle_visibility();">toggle</a> 

EDIT3 EDIT3

Ah, I found the problem :) 啊,我发现了问题:)

if(document.getElementsByTagName("ol")[0].style.listStyle.substr(0,4) == 'none')

Because when you set the listStyle to 'none' it actually gets set to 'none outside none' by firefox and IE. 因为当你将listStyle设置为'none'时,它实际上被firefox和IE设置为'none outside none'。 So if you use .substr(0,4) to get the first 4 characters to compare to none, you should be fine :) 所以,如果你使用.substr(0,4)来获得前4个字符来比较没有,你应该没问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM