浅谈实现网页交替背景颜色的几种方法

WordPress 的评论模板部分都会定义一个$oddcomment函数用来实现评论的样式交替变换,采取交替样式可以使列表有一定分区度,便于浏览。我稍稍总结了下,分别通过javascript, phpCSS三种方式进行实现,其中CSS实现方法还几乎处于理想状态,仅供参考。

实现方法之Javascript篇

假设我们有个id名为 list 的无序列表ul,其下有5项item (li)。我们可以用getElementByIdgetElementsByTagName先找到这些item,然后通过for循环筛选出奇数项并赋予class值。再通过CSS定义该奇数项class样式从而达到交替样式的目的。javascript代码如下:

 function alterItem() {
 var list=document.getElementById('list');
 var items=list.getElementsByTagName('li');
 for (var i=0;i<items.length;i++) {
   if(i%2==0)
   items[i].className='odd';
   }
 }

 window.onload=alterItem;

最后用通过CSS定义 .odd样式就行了。
Read More

You Might Know

This site is powered by WordPress CMS & hosted by Dreamhustle Dreamhost.

And the theme is inspired by WP Typo and completely crafted under Gentoo Linux with VIM editor.

Sponsors

Monthly Archives

Search