如何在运行时使用jQuery更改样式属性值

时间:2019-01-25 00:22:36

标签: jquery html css3

当屏幕尺寸变为1199像素时,这是我的<img>标签:

<img id='rotateimage' src='images/01/0001.jpg' width='1200' height='700'>

我想更改宽度和高度,例如:width: 1000; height:500,并在屏幕尺寸变为1199px时减小宽度和高度。

这是正在做的事,但不起作用:

if ($screen_width <= 1199){

    $width2 = 1000;
    $height = 500;

}

$("img").attr('width', '$width2');
$("img").attr('height', '$height');

2 个答案:

答案 0 :(得分:0)

使用CSS设置图像大小,并使用$("img").css("width");进行修改

答案 1 :(得分:0)

您可以按照其他建议使用.css()函数进行此操作,也可以在CSS中定义媒体查询。

jQuery

function res() {
  if ($window.width() <= 1199) {
    $("#rotateimage").prop("width", 1000).prop("height", 500);
  } else {
    $("#rotateimage").prop("width", 1200).prop("height", 700);
  }
}

$( window ).resize(function() {
  res();
});

CSS中的媒体查询

#rotateImage {
  width: 1200px;
  height: 700px;
}

 @media only screen and (max-width: 1199px) {
  #rotateImage {
    width: 1000px;
    height: 500px;
  }
}
相关问题