简体   繁体   English

调整浏览器大小时如何获取选定的div宽度

[英]How to get selected div width when resize browser

I want to get selected div width according to following algorithm: 我想根据以下算法获得选定的div宽度:

  1. If user resize browser then get div width according to resize browser div. 如果用户调整浏览器大小,则根据调整浏览器div的值获得div宽度。

  2. If user don't resize browser then get div width normally. 如果用户不调整浏览器的大小,则通常会获得div宽度。

Here is my code 这是我的代码

jQuery(document).ready(function($) {

    if ($(window).resize) {
        var width = $('#main_header .wrapper').width($(window).resize);
    }
    else {
        var width = $('#main_header .wrapper').width;
    }

});

My code don't work, Please, any one can help me solving this problem. 我的代码无效,请任何人都可以帮助我解决此问题。 Thanks 谢谢

Your use of if is the problem. 您使用if是问题所在。 Try this: 尝试这个:

jQuery(document).ready(function($) {
  $(window).resize(function() {
    alert("$('#main_header .wrapper').width());
  })
});

$(window).resize will always return true because resize is a jQuery function. $(window).resize始终返回true,因为resize是一个jQuery函数。 This code instead watches window for a resize event and calls the inner function when it happens. 该代码改为监视window以查看resize事件,并在事件发生时调用内部函数。

I didn't fill in the inner function because I wasn't clear on what you wanted to happen upon resize. 我没有填写内部函数,因为不清楚在调整大小后要发生什么。

This little function will get the width of #main_header .wrapper and update it on resize: 这个小功能将获得#main_header .wrapper的宽度,并在调整大小时对其进行更新:

$(function() {
    var $wrapper = $('#main_header .wrapper');//the element we want to measure
    var wrapperWidth = $wrapper.width();//get its width    
    $wrapper.text(wrapperWidth);//dunno what you want to do with wrapperWidth but here im setting it as the text of .wrapper just so you can see the value changing
    //add resize listener
    $(window).resize(function() {
        wrapperWidth = $wrapper.width();//re-get the width
        $wrapper.text(wrapperWidth);//update the text value
    });
});

Here's a working demo: http://jsfiddle.net/5rZ4A/ 这是一个工作示例: http : //jsfiddle.net/5rZ4A/

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

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