首页 > 解决方案 > 模拟宽度:calc(100%) - jQuery 不工作

问题描述

我正在使用 HTML、CSS、mediaQuery、Javascript、jQuery 和 PrimeFaces,并且我想使用 css 属性

calc(100% - 100px)

我已经为不支持此属性的旧浏览器实现了 javascript 解决方法。

在阅读了几个相关问题后,例如:

我的代码摘录:

1.) 我的 facelet 中的 JavaScript 函数:

        <ui:define name="search_results">
        <h:outputStylesheet name="primeicons/primeicons.css" library="primefaces"/>
        <h:outputStylesheet library="css" name="results.css" />
        <h:outputScript library="primefaces" name="jquery/jquery.js"/>
        <h:outputScript library="js" name="results.js"/>
        <script>
            // we need to execute the js function after the page load:
            // @see https://stackoverflow.com/questions/8996316/how-to-execute-javascript-after-page-load
            jQuery(document).ready(function() {
                jQuery(document).ready(function() {
                    // twice in document.ready to execute after Primefaces callbacks
                      document.getElementById("homeDetailsPanelId").setAttribute("style","width:583px !important;");
                      var width = document.getElementById("homeDetailsPanelId").style.width;

                      alert (width);
                });
            }); 
        </script>

2.) 我有问题的元素的 HTML 和 CSS 代码:

 <div id="homeDetailsPanelId" class="col-7">
 <!-- more code here -->
 </div>

3.)我的css文件:

    @media only screen and (min-width: 1200px) {

    .col-7 {
        width:calc(100% - 395px);
    }

     /* more styles here */
   }

最小的工作示例:

https://github.com/alexmivonwien/pf.css

当我在任何浏览器中加载我的页面时,我看到 javascript 被执行并且元素的宽度设置正确。但是,在alert()显示 javascript 并确认后,浏览器会应用媒体查询中的 css,并且使用 javascript 设置的元素的宽度被覆盖。

如何让我的 JavaScript 优先于 CSS 中的媒体查询?

当前结果:

在此处输入图像描述

标签: javascriptjqueryhtmlcss

解决方案


这可能是 id 和 class 主席的问题。尝试在 jquery 中给出 class 并在 CSS 中给出 id

css

    @media only screen and (min-width: 1200px) {

    #homeDetailsPanelId {
        width:calc(100% - 395px);
    }

     /* more styles here */
   }

查询:

   document.getElementByClassName("col-7").setAttribute("style","width:583px !important;");
                    


推荐阅读