调用#DIV上的函数,而不是window()

Calling function on #DIV rather than window()

本文关键字:window #DIV 函数 调用      更新时间:2023-09-26

我写了这个脚本,它有效地隐藏了一个依赖于浏览器的工具栏window().width。我后来意识到,由于我想计算宽度的方式……:

'$csspagewidth2=$Cspagewidth*2;'

我可以用#DIV.width来代替window().width。但当我试图将window(.width)更改为#main content时。它无法工作。有人能帮忙吗?

if ($("#main-content").width() < 600) {
       $( "#toolbarright").hide();
}
else {
        $("#toolbarright").show();
}
$("#main-content").resize(function() {
   windowWidth = $(this).width();//you need to use this for changable values
   if ( windowWidth < 600) {
       $( "#toolbarright").hide();
   } else if ( windowWidth > 600) {
        $("#toolbarright").show();
   }
 });

小提琴:http://jsfiddle.net/ablueman/vdgeLsgL/16/

上下文:https://www.ablueman.co.uk/testbench/layout.php

$(main-content)将获取main变量(undefined),并从中减去content变量(也称为undefined),从而获得NaN,然后该变量将用于尝试实例化jQuery对象。它在DOM中找不到任何匹配的元素。

您想要$("#main-content")

使用CSS很容易

@media only screen and (max-width: 320px){
       #toolbarright { display:none; }
}

DEMO1

更新1:

JQuery

$(window).on('resize', function(){
    $('#main-content').each(function(){
        var box = $(this);        
        var width = box.width();
        var height = box.height();
        if ( width < 600) {
            box.find( "#toolbarright").hide();
        } else if ( width > 600) {
            box.find("#toolbarright").show();
        }          
        $('.size').html(width+'x'+height+' (r: '+(width/height).toFixed(3)+')');
    });
}).trigger('resize');

CSS

#main-content 
{
    margin: 120px;
    position: relative;
}
#toolbarright 
{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow:hidden;
    outline: 1px solid grey;
    height:100px;
}

DEMO2

想好了:

$( document ).ready(function() {
if ($("#maincontent").width() < 600){
       $( "#toolbarright").hide();
} else { $("#toolbarright").show();}
});

$(window).resize(function() {
if ($("#maincontent").width() < 600){
       $( "#toolbarright").hide();
} else { $("#toolbarright").show();}
});

http://jsfiddle.net/ablueman/vdgeLsgL/