简体   繁体   English

使用CSS覆盖@media的jQuery样式

[英]Overriding jQuery styling with CSS for @media

I have some jQuery script that positions a sidebar menu to scroll down with the screen: 我有一些jQuery脚本,用于放置侧边栏菜单以在屏幕上向下滚动:

<head>    
<script type="text/javascript">
    jQuery(function($) {
    function fixDiv() {
      if ($(window).scrollTop() > 365)
        { 
        $('#Portfolio-Sidebar-Content-Web').css({'position': 'fixed', 'top': '0', 'margin-top': '20px'}); 
        }
      else
        {
        $('#Portfolio-Sidebar-Content-Web').css({'position': 'static', 'top': 'auto', 'margin-top': '0'});
        }
    }
    $(window).scroll(fixDiv);
    fix5iv();
    });
    </script>
</head>

This works just fine on desktop, but behaves differently when zooming on tablets and mobile as the div is fixed on the screen and overlaps the content. 这在台式机上工作得很好,但是在div和平板电脑上缩放时,行为会有所不同,因为div固定在屏幕上并与内容重叠。

This is where I would like @media query to kick in and position the div differently when on a tablet or mobile device, overriding the styling applied by the jQuery script: (the @media styling is placed at the very bottom of my style sheet) 这是我希望@media查询在平板电脑或移动设备上插入并以不同的方式放置div的地方,覆盖了jQuery脚本应用的样式:( @media样式位于样式表的最底部)

@media only screen and (max-device-width: 480px) {
    #Portfolio-Sidebar-Content-Web{
        position: fixed !important;
        top: 0px !important;
        }
}

However this code wont work for me :/ It seems the jQuery styling will always override any css positioning which I apply, and the div continues to scroll on any device. 但是,此代码对我不起作用:/看来jQuery样式将始终覆盖我应用的所有CSS位置,并且div继续在任何设备上滚动。

You could set the jquery to only take effect if the screen size is as you require; 您可以将jquery设置为仅在屏幕大小符合要求时才生效;

<script type="text/javascript">
    jQuery(function($) {
    if ( $(window).width() > 759) {
    function fixDiv() {
      if ($(window).scrollTop() > 365)
        { 
        $('#Portfolio-Sidebar-Content-Web').css({'position': 'fixed', 'top': '0', 'margin-top': '20px'}); 
        }
      else
        {
        $('#Portfolio-Sidebar-Content-Web').css({'position': 'static', 'top': 'auto', 'margin-top': '0'});
        }
    }
    $(window).scroll(fixDiv);
    fix5iv();
    }
    });
    </script>

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

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