使用jQuery更改img属性

使用jQuery更改img属性,jquery,css,media-queries,Jquery,Css,Media Queries,我不想使用窗口宽度来更改img标记,而是想使用另一个随媒体查询而更改的元素高度。例如,页面加载在全尺寸显示器上,而不是移动或平板显示器上。当窗口缩小并达到800px的断点时,css表将发生变化,名为.content的div标记的高度将变为267px。现在我希望jQuery在.contentjQuery.height是一个方法时更改图像标记的.attr,您需要调用它来获取高度 所以 jQuery的宽度和高度是函数,可以这样使用: $(document).ready(function(){

我不想使用窗口宽度来更改img标记,而是想使用另一个随媒体查询而更改的元素高度。例如,页面加载在全尺寸显示器上,而不是移动或平板显示器上。当窗口缩小并达到800px的断点时,css表将发生变化,名为.content的div标记的高度将变为267px。现在我希望jQuery在.contentjQuery.height是一个方法时更改图像标记的.attr,您需要调用它来获取高度

所以

jQuery的宽度和高度是函数,可以这样使用:

$(document).ready(function(){
      var n = $(".content").height();
      if (n < 268){
          $("#pictureOne").prop("src","medium.jpg").width(400).height(267);

      }else if (n < 135) {
          $("#pictureOne").prop("src","medium.jpg").width(200).height(134)
      } 
});
请注意,条件中也缺少括号,您应该使用prop来更改属性,如src。

尝试此解决方案

CSS

HTML


尝试prop方法并包含在load函数中谢谢您的帮助和代码。我已经更新了我的代码,但仍然无法正确更改我的图像。非常感谢Rakesh为您提供的时间和帮助。
        Small
.content {position: relative; margin: 0px auto; width: 200px; height: 134px; border: 1px solid black;}

Medium
.content {position: relative; margin: 0px auto; width: 400px; height: 267px; border: 1px solid black;}

Large
.content {position: relative; margin: 0px auto; width: 700px; height: 467px; border: 1px solid black;}
var n = $(".content").height();
$(document).ready(function(){
      var n = $(".content").height();
      if (n < 268){
          $("#pictureOne").prop("src","medium.jpg").width(400).height(267);

      }else if (n < 135) {
          $("#pictureOne").prop("src","medium.jpg").width(200).height(134)
      } 
});
/* Large Media Query */
.content {position: relative; margin: 0px auto; width: 700px; height: 467px; border: 1px solid black;}

@media only screen and (max-width: 500px) {
    /* Small Media Query */
    .content {height: 267px;}
}

@media only screen and (max-width: 300px) {
    /* Small Media Query */
    .content {height: 134px;}
}
<div class="content">
    <img id="pictureOne" src="https://cdn3.iconfinder.com/data/icons/iconic-1/32/check_alt-48.png" >
 </div>
function setLayout(){

      var n = $(".content").height(),
            url = 'https://cdn3.iconfinder.com/data/icons/iconic-1/32/';
    switch(n){
        case 134:
            $("#pictureOne").attr("src", url+"check_alt-24.png");
            break;
        case 267:
            $("#pictureOne").attr("src", url+"check_alt-32.png");
            break;
        default:
            $("#pictureOne").attr("src", url+"check_alt-48.png");
    }

};

$(document).on('resize ready', function(){ setLayout() });
$(window).on('resize', function(){ setLayout() });