【问题标题】:How to change media query CSS with jQuery如何使用 jQuery 更改媒体查询 CSS
【发布时间】:2019-08-14 04:31:01
【问题描述】:

我有两个背景图片,我想用 jQuery 来改变它。

对于#banner 它可以工作,但我现在不知道如何为@media screen and (max-width: 1024px) 编写代码

.banner {
  background: url(../images/640px.jpg) 0px 0px no-repeat;
}

@media screen and (max-width: 1024px) {
  .banner {
    background: url(../images/900px.jpg) 0px 0px no-repeat;
  }
}
var selectData = {

  "bmw": {

    "1": "316i",
    "100": "520i",
    "101": "740i",
    "image1": "images/640px.jpg",
    "image2": "images/900px.jpg",

  },

};

jQuery(document).ready(function($) {
  $(document).on('click', '.specialLink', function(event) {
    var radio2 = document.getElementById('radio2');
    if (radio2.checked == false) {
      radio2.checked = true;
      toggleRadio();
    }
    $(".regio").html($(this).text());
    event.preventDefault();
    var b = $(this),
      background_image = '';
    buttonId = b.attr('id'),
      selectSet = selectData[buttonId],
      selectField = $('#specialLink');
    selectField.empty();
    //To change the background image of website
    $("#banner").css('background-image', 'url("' + selectSet.image1 + '")');
    $("@media screen and (max-width: 1024px)").css('background-image', 'url("' + selectSet.image2 + '")');
    if (selectSet) {
      //Remove image index form selectSet
      $.each(selectSet, function(k, v) {
        if (typeof k === 'string' && k === 'image') {
          return true;
        }
        selectField.append($('<option>', {
          value: k,
          text: v
        }));
      });
    }
    return false;
  });
});

【问题讨论】:

标签: javascript jquery css media-queries


【解决方案1】:

你可以使用jQuery(window).resize()函数,它会在浏览器窗口调整大小时触发。

这是一个使用 jQuery、javascript 和 css 处理调整大小事件的示例。 (如果您只是在调整大小(媒体查询)时对事物进行样式化,那么最好的选择是css) http://jsfiddle.net/CoryDanielson/LAF4G/

将此代码用于您需要的解决方案。

$(window).resize(function(){
    if ($(window).width() <= 1024){ 
        $('.banner').css('background-image', 'url(' + imageUrl + ')');
    }   
});

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    您可以使用html5的图片标签更改图像

    <picture>
        <source media="(min-width: 650px)" srcset="img1.jpg">
        <source media="(min-width: 465px)" srcset="img2.jpg">
        <img src="img3.jpg">
    </picture>
    

    【讨论】:

      猜你喜欢
      • 2021-02-27
      • 1970-01-01
      • 2021-08-21
      • 2011-09-21
      • 1970-01-01
      • 2021-04-01
      • 2014-05-20
      • 2020-03-04
      • 2013-06-13
      相关资源
      最近更新 更多