我在未排序列表中有一些图像。
<ul>
<li id='chain'>
<a href="">
<span class='fade'></span>
<div class='title'>TITLE</div>
<img src="img/bike/chain.jpg" alt="" width="550" height="440" />
</a>
</li>
<li id='grips'>
<a href="">
<span class='fade'></span>
<div class='title'>TITLE</div>
<img src="img/bike/grips.jpg" alt="" width="275" height="440" />
</a>
</li>
<li id='tires'>
<a href="">
<span class='fade'></span>
<div class='title'>TITLE</div>
<img src="img/bike/tires.jpg" alt="" width="175" height="220" />
</a>
</li>
</ul>
我需要 CSS 来为每个集合中的跨度和div 提供相同的宽度,就像在循环中表示的那样,而不是手写每个项目
#chain .fade, #chain .title {width:550px}
#grips .fade, #grips .title {width:275px}
#tires .fade, #tires .title {width:175px;}
问:我可以使用jQuery动态创建CSS吗?如果不是,我如何创建这个CSS并使用PHP分配宽度值?
列表项会经常更改,我希望使用循环或 .each 语句。
换句话说,我不想列出每个项目
有没有办法拉取 li ID 和 IMG 维度并动态创建 CSS
伪代码:
var w = $('ul li').each(find img width).assign it to> .css(this .fade, this .title {width:w + "px"});
或
我应该研究PHP来回显每个ul li IMG的输出吗?
jQuery可以轻松地创建内联CSS样式(应用于每个元素的样式)。
$('#chain, #grips, #tires').each(function(index, element){
$('.fade', element).width( $('img', element).width() );
});
这是这个脚本正在做的事情
.each()
循环访问所有选定的元素。 顾名思义,index
是正在迭代的数组的索引。 element
是正在迭代的当前元素。
$('.fade', element)
,这将查找元素中的fade
类。
.width()
将获取或设置元素的宽度。如果将参数传入其中,则将设置它,例如:.width(15)
.(这会将元素的宽度设置为 15 像素宽。如果没有任何内容传入元素,它会检索元素的宽度,例如:.width()
.
$('img', element).width()
检索元素内 img 标记的宽度。因为这个值被传递到$('.fade', element).width()
,它会设置元素的类为淡入淡出到img的宽度。
这是使用 jQuery 的方法:
$('li').each(function(){
var $li = $(this);
var $img = $li.find('img');
var width = $img.attr('width');
$li.find('.fade, .title').css('width', width + 'px');
});
或者去掉jQuery,只使用css:
li { float: left; clear: left; }
http://jsfiddle.net/u2HNx/2/
好的,试试这个:
$('li').each(function(){
var width = $(this).find('IMG').width();
$(this).find('.fade').width(width);
$(this).find('.title').width(width);
});
$("#chain .fade,#chain .title").css('width','550px');