如何使下拉菜单的宽度与触发按钮的宽度相同

时间:2014-07-25 20:57:34

标签: javascript jquery

在图像中,这是我正在努力实现的目标:

enter image description here

这就是我开始使用js的方式:

$(document).ready(function(){
            var userWidth = $('#userOptions.width()');
            var menuWidth = $('#userOptionsMenu.width()')


            function menuMatch() {
                if(menuWidth < userWidth) {
                    menuWidth = userWidth;
                }
            }

            menuMatch();

        });

这是ID为的图像:

enter image description here

在函数menuMatch()中,我不知道如何用JS编写如何使宽度与当前比它更窄的元素相等。

这有意义吗?

感谢。

这是指向codepen http://codepen.io/MARS/pen/cGwbC

的链接

2 个答案:

答案 0 :(得分:1)

您错误地提取了jQuery width属性。改变这个:

var userWidth = $('#userOptions.width()');
var menuWidth = $('#userOptionsMenu.width()')

到此:

var userWidth = $('#userOptions').width();
var menuWidth = $('#userOptionsMenu').width();

这将获得您需要设置的宽度。然后要正确应用css,您需要这样做:

function menuMatch() {
    if(menuWidth < userWidth) {
        $("#userOptionsMenu").css("width", userWidth + "px");
    }
}

答案 1 :(得分:1)

您有两个问题:

1)您在选择器中包含了width()。应该在选择器之后调用该函数。

2)您需要使用width()作为选择器来设置宽度,而不是仅仅将$('#userOptionsMenu').width()设置的变量修改为等于。

$(document).ready(function(){
        var userWidth = $('#userOptions').width();     // These should be
        var menuWidth = $('#userOptionsMenu').width(); // outside of the quotes

        function menuMatch() {
            if(menuWidth < userWidth) {
                $('#userOptionsMenu').width(userWidth); // Change the value of
            }                                           // the width using
        }                                               // width() as a setter.

        menuMatch();
    });