使用现有代码更改基于浏览器宽度的图像url

Changing image url based on broswer width with existing code

本文关键字:浏览器 url 图像 代码      更新时间:2023-09-26

我是JavaScript新手,如果有人问我这个问题,请原谅。

我想让我的img标签有响应,所以我使用这个:

<img data-nsrc="<?php 
                 echo wp_get_attachment_image_src( get_post_thumbnail_id()
                                                 , 'small-post'
                                                 , false )[0] ?>"
     data-msrc="<?php 
                 echo wp_get_attachment_image_src( get_post_thumbnail_id()
                                                 , 'mobile-img', false )[0] ?>"
     src="<?php echo wp_get_attachment_image_src( get_post_thumbnail_id()
                                                , 'small-post'
                                                , false )[0] ?>" 
     class="img-right resimgsm">

我将代码更改为使用img,就像以前使用带有inline CSSbackground imagediv一样。

这是运行在页面底部的script

<script>
jQuery(document).ready(function(){
    jQuery( window ).resize(function(ev) {
      var w=jQuery( window ).width();
      if(w>600){
        jQuery.each(jQuery('.resimgsm'),function(i,el){
            jQuery(el).attr('src',"background-image: url('"+jQuery(el).attr('data-nsrc')+"')")
        })
      }else{
        jQuery.each(jQuery('.resimgsm'),function(i,el){
            jQuery(el).attr('src',"background-image: url('"+jQuery(el).attr('data-msrc')+"')")
        })
      }
    });
    jQuery(window).trigger('resize')
})  
</script>

有人能教我如何改变这一点吗?谢谢你的帮助。

更改图像源与之前的非常相似,只需要直接的图像URL:

  if(w>600){
    jQuery.each(jQuery('.resimgsm'),function(i,el){
        jQuery(el).attr('src',jQuery(el).attr('data-nsrc'))
    })
  }else{
    jQuery.each(jQuery('.resimgsm'),function(i,el){
        jQuery(el).attr('src', jQuery(el).attr('data-msrc'))
    })
  }

简介

你以前的样子可能是:

<div style="background-image: url(imageURLHere.jpg);"></div>

并且您正在修改样式属性或CSS属性。

你现在的样子应该是:

<img src="imageURLHere.jpg">

上面的代码就是这样做的。