HTML,jQuery:将一个元素的宽度绑定到另一个元素 [英] HTML, jQuery: Bind width of one element to another

查看:952
本文介绍了HTML,jQuery:将一个元素的宽度绑定到另一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将第一个元素(foo)的宽度绑定到第二个元素(bar)的宽度。我希望元素foo在元素bar的宽度发生变化时自动改变宽度。



我知道我可以设置元素foo的宽度到元素bar的宽度,我们可以在下面的代码中看到,但这是一次性的事情。执行此代码后,如果元素bar的宽度在页面处理中的某处发生更改,会发生什么情况?例如bar是一个select元素,其宽度因AJAX调用而改变 - 元素foo将如何改变其宽度?

 <$ 。C $ C> $( '#富')宽度($( '#巴')宽度()); 

谢谢

解决方案 div>

Resize事件只绑定到窗口而不是像divs这样的元素,
在这里完整讨论: jQuery调整大小不适用于FireFox,Chrome和Safari



唯一的解决方案是让一个全局变量,并在更改条形大小时使用它来更新。 foo的宽度设置为全局变量。在更新bar大小的方法或代码块中添加代码,直接使用$(foo).width($ bar.width())更新全局变量或foo大小;

 函数setBarHeight(value){
$('#bar')。attr('width')= Number(value);
$('#foo')。attr('width')= $('#bar')。attr('width');
}

编辑:下面这个jQuery方法不起作用, 。



调整大小添加jquery处理程序

  $(document).ready(function(){
$('#bar')。resize(function(){
$('#foo')。width($('#bar')。width());
});
});


I'd like to bind the width of a first element (foo) to the width of a second element (bar). I would want element "foo" to have its width change automatically when the width of element "bar" is changed.

I know I can set the width of element "foo" to the width of element "bar" as we can see in the code below, but this is a one-time thing. What happens if the width of element "bar" changes somewhere in the processing of the page after this code is executed? e.g. "bar" is a select element and its width changes as a result of an AJAX call - how would element "foo" get its width changed?

$('#foo').width($('#bar').width());

Thanks

解决方案

Resize events are bound only to the window and not to elements like divs, full discussion here: jQuery resize not working at FireFox, Chrome and Safari

The only solution would be to have a global variable and use it to update when bar size is changed. foo's width is set to the global variable. Add code in the method or code block that updates bar size, to update the global variable or the foo size directly using $(foo).width($bar.width());

function setBarHeight(value) {
   $('#bar').attr('width') = Number(value);
   $('#foo').attr('width') =  $('#bar').attr('width');
}

EDIT: This jQuery approach below doesn't work, updated answer above this line.

Add jquery handler for resize

$(document).ready(function() {
    $('#bar').resize(function() {
        $('#foo').width($('#bar').width());
    });
});

这篇关于HTML,jQuery:将一个元素的宽度绑定到另一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆