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

jQuery - use css in if statement argument

我在之前的 div 中使用 vw,现在我想在 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.

pxvw的转换参考

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

例如 — 如果您的视口为 500px 宽(根据定义等于 100vw)则

1px = (100 / 500) = 0.2vw

另外你有语法错误..请正确处理引号

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

数值单位有问题。左轴为 px,右轴为 vw

1px = 100 / document.documentElement.clientWidth + 'vm';

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!');
}
#pagination{
  margin-left:-84vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='pagination'>some stuff</div>

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

中的宽度

只需更改条件逻辑即可。

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

您可以使用边距值的符号进行额外控制。

//Compute the percent width of the element's container
var width = $('#container-of-pagination').width();
var parentWidth = $('#container-of-pagination').offsetParent().width();
var percent = 100*width/parentWidth;
//This will be used for the extra control.
var margin = parseInt( $('#pagination').css('margin-left') );
if ( percent == 84 && margin < 0 ) {
    alert('you\'re good to go!');
}