javascript - 通过调整页面宽度来更改图像

标签 javascript html image resize width

我需要一些有关此 JavaScript 代码的帮助,我对使用 javascript 很陌生,所以当我遇到困难时,它会变得很烦人。 我想做的是在小屏幕(手机)上更改导航栏上显示的图像,因为导航栏颜色发生了变化。到目前为止,我通过在线搜索得出的结论是,有些播放仅在手动缩小屏幕尺寸然后图像发生应有的变化时才起作用。但是我希望它也能在这种状态下加载,这就是我陷入困境的地方。

$(window).on('resize', function(){
  var win = $(this);
  if (win.width() < 768) { 
      $(".navbar-brand img").attr('src', 'img/icons/logowhite.png');
  } else {
    $(".navbar-brand img").attr('src', 'img/icons/logodark.png');
}});

这是否可以在 css 中完成,这也是我的一个问题?

最佳答案

demo in fiddle

JS

function resize(){
    if ($(window).width() < 768) { 
      $(".navbar-brand img").attr('src', 'https://www.google.com/images/srpr/chrome_ntp_white_logo2.png');
  } else {
    $(".navbar-brand img").attr('src', 'https://www.google.com/images/srpr/logo11w.png');
  }
}
resize();
$(window).on('resize', resize);

HTML

<div class='navbar-brand'>
    <img src=''/>
</div>

关于javascript - 通过调整页面宽度来更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29617177/

相关文章:

javascript - jQuery 日期选择器中的跳转年份值

javascript - 如何避免将焦点移至 Chrome 扩展程序中的 Google 搜索栏?

javascript - 获取Firefox中某个标签的高度,我设置为display : table; in CSS

javascript - 是否可以在客户端和服务器端设置 td 的宽度?

javascript - IE8默认图片大小

javascript - Bootstrap 选项卡事件选项卡颜色

javascript - 从服务器获取数据,保存在 'state' 中,然后在卡片上显示 'react-trello'

javascript - 获取表格中的行号并将其保存到php变量中

.net - 如何访问位图图像中的每个字节

javascript - MVC3 javascript图像问题