如何根据选定的选项更改选择元素的宽度? [英] How to change width of the select element as per the selected option?

查看:132
本文介绍了如何根据选定的选项更改选择元素的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大量的下拉菜单。
某些选项的文字非常大。我想根据选定的选项制作所选元素的宽度。

如果选择的选项是Selected,那么宽度应该是120px或者其他东西。
当用户选择Very Large Selected选项时,< select> 标签的宽度应该增加。



这里是示例代码,我正在尝试做什么。
http://jsbin.com/axaka4/edit


使用一些作弊你可以克隆选定选项的内容,测量它的宽度并调整大小选择这样的宽度:
$
b $ b

  $('select')。change(function(){
var $ opt = $(this).find(option:selected);
var $ span = $('< span>')。addClass('tester')。text($ opt.text());

$ span.css({ b $ b'font-family':$ opt.css('font-family'),
'font-style':$ opt.css('font-style'),
'font-重量':$ opt.css('font-weight'),
'font-size':$ opt.css('font-size')
});

$('body')。append($ span);
// 30px用于选择打开的图标 - 它可能会因浏览器的不同而有所不同
$(this).width($ span。 width()+ 30);
$ span.remove();
});

$('select')。change();

在这里工作的小提琴


I have large list of the drop-down menu. Some of the option have very large text. and I want to make the width of the selected element as per the selected option.

If the selected option is "Selected" then width should be like 120px or something. When user select "Very Large Selected option" then widht of the <select> tag should be increase.

Here is the sample code, what I am trying to do. http://jsbin.com/axaka4/edit

解决方案

Using some cheating you could clone content of the selected option, measure it's width and resize select to this width like this:

$('select').change(function(){
    var $opt = $(this).find("option:selected");
    var $span = $('<span>').addClass('tester').text($opt.text());

    $span.css({
        'font-family' : $opt.css('font-family'),
        'font-style' : $opt.css('font-style'),
        'font-weight' : $opt.css('font-weight'),
        'font-size' : $opt.css('font-size')
    });

    $('body').append($span);
    // The 30px is for select open icon - it may vary a little per-browser
    $(this).width($span.width()+30);
    $span.remove();
});

$('select').change();

A working fiddle here

这篇关于如何根据选定的选项更改选择元素的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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