Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/88.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果宽度等于百分比,则jQuery_Jquery - Fatal编程技术网

如果宽度等于百分比,则jQuery

如果宽度等于百分比,则jQuery,jquery,Jquery,我知道,以像素为单位,你可以做这类事情,但以百分比为单位,不会返回任何东西。如果我的CSS使用百分比,我将如何处理这个问题?我基本上需要查看具有特定值的div,然后启动脚本的变体 jQuery: if ($(".modPopUp").css("width") == "32%" ){ console.log("32%"); $(".modPopUp:nth-child(3n-2)").css('margin-left', '0'); } else if ($(".modPopUp"

我知道,以像素为单位,你可以做这类事情,但以百分比为单位,不会返回任何东西。如果我的CSS使用百分比,我将如何处理这个问题?我基本上需要查看具有特定值的div,然后启动脚本的变体

jQuery:

if ($(".modPopUp").css("width") == "32%" ){
    console.log("32%");
    $(".modPopUp:nth-child(3n-2)").css('margin-left', '0');
}
else if ($(".modPopUp").css("width") == "49%" ){
    console.log("49%");
    $(".modPopUp:nth-child(2n)").css('margin-left', '0');
}

试着在你的条件之前计算你的元素在px中的百分比

诸如此类:

var width = $('.modPopUp').width();
var parentWidth = $(document).offsetParent().width(); //Document or the element you want
var percent = 100*width/parentWidth;
及之后:

if ($(".modPopUp").css("width") == percent ){
如果您有一个div(或您确实关心其中一个div),您可以执行以下操作: 使用jQuery选择元素,然后从选择器中获取HTML元素,它是选择器中的第一个元素。然后可以使用元素的style属性来获取元素的CSS

例:


通过这种方式获取宽度将始终以像素为单位返回它,无论您如何设置它,因为它是相同的。
.width()
也是如此。您需要计算出它的父对象的宽度

类似以下的操作可以:

Math.floor(($el.width()/$el.parent().width())*100)+"%"
您甚至可以将其放入自己的插件中:

$.fn.widthPerc = function(){
    var parent = this.parent();
    return ~~((this.width()/parent.width())*100)+"%";
}
被称为:

if ($(".modPopUp").widthPerc() == "32%" ){

if ($(".modPopUp").widthPerc() == "32%" ){