简体   繁体   English

如何将@media应用于通过jquery设置的CSS属性

[英]How to apply @media for css attribute that are set via jquery

My website is responsive, I've set a CSS attribute via jQuery, But there is a problem, when I use of @media (for mobile display), that attribute does not change, why ? 我的网站响应灵敏,我通过jQuery设置了CSS属性,但是有一个问题,当我使用@media (用于移动显示)时,该属性没有改变,为什么?

HTML code: HTML代码:

<div class="test">foo</div>

JQuery code: jQuery代码:

$(".test").css({'margin' : '20px'});

CSS code: CSS代码:

@media (max-width: 599px){
   .test {margin: 10px;}
}

Why @media does not works? 为什么@media不起作用? And how it works ? 以及它是如何工作的?

It should be noted that the output is always margin : 20px (for all @media size) 请注意,输出始终为margin : 20px (适用于所有@media尺寸)

Because JavaScript, and by further extension jQuery, adds CSS styles inline, so they take precedence over any styles that are applied in your stylesheet. 因为JavaScript以及进一步扩展的jQuery都添加了内联CSS样式,所以它们优先于样式表中应用的所有样式。

Use another class rather than using .css() : 使用其他类而不是使用.css()

.margin{
  margin: 20px;
}

@media (max-width: 599px){
   .test {margin: 10px;}
}

And then add the class using jQuery and .addClass() : 然后使用jQuery和.addClass()添加类:

$(".test").addClass('margin');

 .test {border:1px solid #000} @media (max-width: 1024px){ .test {margin: 20px;} } @media (max-width: 599px){ .test {margin: 10px;} } 
 <div class="test">foo</div> 

Because you are trying to overwrite javascript CSS (applied with jQuery) with css CSS. 因为您正在尝试使用CSS CSS覆盖javascript CSS(适用于jQuery)。 CSS applied by javascript has always priority. javascript应用的CSS始终具有优先权。

Jquery applies it's css on the element, which has a higher importance than your class in css...if you really need to, you can add .test {margin: 10px !important;} in that media query of yours. jQuery将css应用于元素上,该元素比css中的类具有更高的重要性...如果确实需要,可以在您的媒体查询中添加.test {margin: 10px !important;} hope this helps 希望这可以帮助

You have to specify a @media type, for example : 您必须指定一个@media类型,例如:

@media screen and (max-width 768px) {
//Your declaration here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM