通过调整浏览器窗口条件来更改img src

时间:2017-08-22 20:04:21

标签: javascript html wordpress responsive-design responsive

我正在为我的同事在WordPress cms上创建一个网站,我对主题进行了一些更改。

我的问题是,如何通过调整窗口大小来更改图像src(响应)?

我的徽标图片:

<a href="http://www.ewacieslikiewicz.com/" class="eram-logo" rel="home" 
itemprop="url"><img src="http://www.ewacieslikiewicz.com/wp-
content/uploads/2017/08/cropped-Zrzut-ekranu-2017-07-11-o-13.13.20.png" 
alt="EWA CIEŚLIKIEWICZ" class="ol-retina"></a>

本网站上有人写道,以下代码是完美的:

 $(function resize(){
     if ($(window).width() < 768) { 
      $(".eram-logo img").attr('src', 'http://www.ewacieslikiewicz.com/wp-content/uploads/2017/08/cropped-Zrzut-ekranu-2017-07-11-o-13.13.20.png');
 } else {
      $(".eram-logo img").attr('src', 'http://emonitoring.poczta-polska.pl/hermes/themes/poczta-polska/skin/logo.png');
  }
}
resize();
$(window).on('resize', resize);
    }
});

不工作....

3 个答案:

答案 0 :(得分:1)

我略微纠正了你的功能。这应该工作正常!

&#13;
&#13;
//resize function
function resize() {
  if ($(window).width() < 768) {
    $(".eram-logo img").attr(
      "src",
      "http://www.ewacieslikiewicz.com/wp-content/uploads/2017/08/cropped-Zrzut-ekranu-2017-07-11-o-13.13.20.png"
    );
  } else {
    $(".eram-logo img").attr(
      "src",
      "http://emonitoring.poczta-polska.pl/hermes/themes/poczta-polska/skin/logo.png"
    );
  }
}

//function call when window resized
$(window).on("resize", resize);
&#13;
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
  <title>Document</title>
</head>

<body>
  <a href="http://www.ewacieslikiewicz.com/" class="eram-logo" rel="home" itemprop="url">
    <img src="http://www.ewacieslikiewicz.com/wp-content/uploads/2017/08/cropped-Zrzut-ekranu-2017-07-11-o-13.13.20.png" alt="EWA CIEŚLIKIEWICZ" class="ol-retina">
  </a>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:

$(function() {
$(window).resize(function() {
    if ($(window).width() < 768) {
            $(".eram-logo img").attr('src', 'http://www.ewacieslikiewicz.com/wp-content/uploads/2017/08/cropped-Zrzut-ekranu-2017-07-11-o-13.13.20.png');
        }
        else {
            $(".eram-logo img").attr('src', 'http://emonitoring.poczta-polska.pl/hermes/themes/poczta-polska/skin/logo.png');
        }
    });
});

答案 2 :(得分:0)

这可以在不需要jQuery的情况下工作(我喜欢在可能的情况下将外部依赖关系保持在最低限度):

function resizeListener(e){
  var greaterThanSrc = 'test1';
  var lessThanSrc = 'test2';
  var el = document.querySelector('.eram-logo img');
  var curSrc = el.src;
  if (window.innerWidth < 768 && curSrc != lessThanSrc)
      el.src = lessThanSrc;
  else if (window.innerWidth > 768 && curSrc != greaterThanSrc)
      el.src = greaterThanSrc;  
}

window.addEventListener('resize', resizeListener);