jQuery - 在if语句参数中使用css

时间:2016-02-02 06:15:49

标签: javascript jquery html css viewport

我正在使用vw用于以前的div,现在我想设置一个警告,如果div被移动到最左边。这是div:

<div id='pagination'>some stuff</div>

现在它的宽度设置为84vw,这是从早期函数计算出来的。当它的margin-left等于-84vw时,我想要发出警报。我在js尝试了这个,但没有运气:

if ($('#pagination').css('margin-left') == '-84vw') {
    alert('you're good to go!');
}

有谁可以帮我解决这个问题?真正令人头疼的是我无法将vw更改为px

4 个答案:

答案 0 :(得分:7)

要转换pxvw,请参阅this

  

1px =(100 / document.documentElement.clientWidth)vw

例如 - 如果您的视口为500px宽(根据定义等于100vw),那么

  

1px =(100/500)= 0.2vw

另外,您遇到语法错误。请正确处理引号

alert('you\'re good to go!');

答案 1 :(得分:0)

价值单位存在问题。 LHS为px,RHS为vw

  

1px = 100 / document.documentElement.clientWidth +&#39; vm&#39;;

&#13;
&#13;
var onePx = 100 / document.documentElement.clientWidth;
var valPX = $('#pagination').css('margin-left');
var valVW = Math.round( parseInt( valPX.replace(/[^-\d\.]/g, ''), 10 ) * onePx);
if ( valVW == -84) {
    alert('you\'re good to go!');
}
&#13;
#pagination{
  margin-left:-84vw;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='pagination'>some stuff</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您无法将像素与vw进行比较,因为jQuery.css()始终返回pixels

中的宽度

答案 3 :(得分:0)

只需更改条件逻辑。

边距的值取决于容器宽度,因此您可以使用容器的宽度值更改元素的vw值,并使用它来进行比较。

您可以使用保证金值的符号进行额外控制。

<!DOCTYPE html>
      <html>
            <head>
                <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
       <script>
                     angular.module('dash',[]).filter('removeDashes',function(){
                         return function(text){
                            if(text!==undefined){
                                 return text.split('-').join(' ');
                             }
                         }
                     });
angular.module('appModule', ['dash']).controller('someCTRL', function($scope){
                     });
                </script>
             </head>

             <body ng-app="appModule" ng-controller="someCTRL">
            <input type="text" ng-model="someDashedText">
            <p>
                {{someDashedText|removeDashes}}
            </p>
        </body>
    </html>
相关问题