简体   繁体   English

如何检查元素宽度是否大于100%

[英]How to check if element width is greater than 100%

I want to check if my element is greater than 100% in width - so if the div is 113.42% hide something else, but I cannot get it to hide elements. 我想检查我的元素是否大于100%的宽度-因此,如果div为113.42%,则可以隐藏其他内容,但是我无法隐藏元素。

Right now, I have this set up to test, if the width is greater than 100% make background black else make background red. 现在,我已经对此进行了测试,如果宽度大于100%,则将背景设为黑色,否则将背景设为红色。 Right now, the elements are red but the elements that are greater than 100% are not turning black. 目前,元素为红色,但大于100%的元素不会变黑。 Can someone pin point what I am doing wrong? 有人可以指出我做错了什么吗? It is also doing it to all elements I want to detect on each element with .display-area - do I have to use the .each function? 它也对要在.display-area上每个元素上检测到的所有元素都执行此操作-我必须使用.each函数吗?

        var $displayarea = $(".display-area");
        var width = $('.display-area').width();
        var parentWidth = $('.display-area').offsetParent().width();
        var percent = 100*width/parentWidth;
//      var per = $('.first-div').width() * .80;
//      if ( $displayarea.width() > "100%" )  {
        if ($displayarea.css("width") > percent ) {
                $displayarea.css({ 
                        background: 'black'
                });

        } else {

                $displayarea.css({
                        background: 'red'
                });

        }

I don't know if this is what you are after, but you can check out a demo here . 我不知道这是您要追求的,但是您可以在此处查看演示。

$(function () {
    var $displayarea = $(".display-area");
    var parentWidth = $('.display-area').parent().width();

    $displayarea.each(function () {
        if ($(this).width() > parentWidth) {
            $(this).css({
                background: 'black'
            });

        } else {
            $(this).css({
                background: 'red'
            });
        }
    });

});

You can compare the widths of the html tag and the element by using their respective css selectors. 您可以使用各自的css选择器比较html标签和元素的宽度。

if($('div').css("width").replace("px","") > $('html').css("width").replace("px",""))
    alert($('div').css("width").replace("px","") - $('html').css("width").replace("px","")  + " more");

Possible here is what you are searching: 可能的是您正在搜索的内容:

var parent = $('.parentDiv').width();
var child = $('.childDiv').width();

var percent = child * 100 / parent;

if (percent > 100) {
   $('.childDiv').css('background-color', '#000')
} else {
   $('.childDiv').css('background-color', '#f00')
}

you need check on resize event 您需要检查调整大小事件

like $('.display-size').bind('resize',function(){
//logic
})

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

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