gpt4 book ai didi

jquery - 使用 jquery/js 查找元素的自动宽度

转载 作者:行者123 更新时间:2023-11-28 19:02:55 24 4
gpt4 key购买 nike

在 IE 中,在 Focus 上,我希望仅在自动宽度比我设置的静态宽度宽的情况下将元素的宽度扩展为 width: auto。我试图避免的只是总是将元素设置为 width: auto 并让元素收缩。我只希望它在必要时扩展。

有没有人有一种干净的方法来检查设置为 auto 时元素的宽度,而无需先设置属性?现在,我设置它,然后检查宽度并可能将其设置回静态,似乎应该有一个更简洁的解决方案。

使用 jquery 的当前代码示例:

$('mySelector').live('focus', function() {
//store the original width, then set the element to width: auto
$(this).data('w', $(this).width()).css('width', 'auto'));
//is the element now shorter? if so, set it back to the original width
if ($(this).width() < $(this).data('w')) {
$(this).width($(this).data('w'));
}
}

最佳答案

不确定您是否会找到更简洁的解决方案,但这里有一个不涉及操作元素本身的解决方案:

function adjustWidth($el) {
var $clone = $el.clone().css({width: "auto", display:"none"}).appendTo($el.parent());
var width = $clone.width();
$clone.remove();

if (width > $el.width()) {
$el.css("width", "auto");
}
}

关于jquery - 使用 jquery/js 查找元素的自动宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4925399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com