javascript - 根据视口(viewport)宽度动态调整图像高度

标签 javascript jquery html css

如何使用 jQuery 使用视口(viewport)的宽度动态更改图像的高度。

举个例子

当网站宽度为 450px 时,我想将图像宽度从 300 更改为 100。

我还使用 timthumb 来调整图像大小。

HTML 代码

<img src="timthumb.php?src=myimage.jpg&amp;h=300&amp;w=750&amp;q=100" class="MyImages">

如何使用 jQuery 来做到这一点?

最佳答案

这应该有效。只需在 jQuery 获取视口(viewport)宽度后添加 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> 

就像这样,当您调整视口(viewport)大小时,所有图像都会更新。

关于javascript - 根据视口(viewport)宽度动态调整图像高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25347578/

相关文章:

html - 如何使div宽度适合div内的表格?

javascript - 编写一个 ruby​​ gem,向 Rails 添加 js 方法

jquery - Jquery选择文件时获取文件列表对象

html - 将表单元素移动到它们看起来堆叠的位置

java - 在表单提交时触发页面加载微调器

javascript - javascript如何调用iframe加载文件的函数

html - 使用 htmlTable 更改表标题颜色

javascript - 使用 componentDidUpdate 更改组件中的状态

javascript - <body> 元素上的 Shadow DOM 是一个坏主意吗?

javascript - 如何不触发路由器中间件