我如何使用jQuery通过视口的宽度动态更改图像的高度。
举个例子
当网站宽度为450px时,我想将图像宽度从300更改为100。
另外,我正在使用timthumb调整图像大小。
HTML代码
<img src="timthumb.php?src=myimage.jpg&h=300&w=750&q=100" class="MyImages">
我如何使用jQuery来做到这一点?
这应该工作。只需在jQuery获取视口宽度后添加src属性,然后在调整窗口大小时对其进行更新。
<img id="img1" src="" class="MyImages">
<script type="text/javascript">
$(function() {
update_image();
$( window ).resize(function() {
update_image();
});
});
function update_image(){
var width = $( window ).width();
if(width<450) { var picwidth=100; } else { var picwidth=300; }
$('#img1').attr('src','timthumb.php?src=myimage.jpg&h=300w='+picwidth+'&q=100');
}
</script>
回答您的问题:编辑图像,如下所示:
<img src="" class="MyImages" data-src="myimage.jpg">
现在,您可以使用jQuery获得正确的尺寸:
<script type="text/javascript">
$(function() {
$('img').each(function(){
update_image(this);
});
$( window ).resize(function() {
$('img').each(function(){
update_image(this);
});
});
});
function update_image(e){
var width = $( window ).width();
if(width<450) { var picheight=100; } else { var picheight=300; }
var image = $(e).attr('data-src');
$(e).attr('src','timthumb.php?src='+image+'&h='+picheight+'&q=100');
}
</script>
这样,在调整视口大小时,所有图像都会更新。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句