简体   繁体   中英

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

It is code highlighted by Geshi, and i build the javascript at the top to toggle line numbers.

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:

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.

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.

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

and

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

EDIT2 Perhaps give this a try. If you could also link me to it, I can test it in chrome and firefox as well. 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

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. So if you use .substr(0,4) to get the first 4 characters to compare to none, you should be fine :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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