【问题标题】:Get text indent of HTML select elements获取 HTML 选择元素的文本缩进
【发布时间】:2022-01-01 22:48:39
【问题描述】:

在 HTML Select 元素中,4px 缩进。

如何使用 JavaScript 计算/获取确切值

我试过了,但没有得到正确的值

const el = document.querySelector('select');
const computedStyle = getComputedStyle(el);
computedStyle.textIndent // '0px'
computedStyle.padding // '0px'

【问题讨论】:

  • 据我所知,这是不可能的。如果您不需要动态地获取此信息,请尝试仅使用 Photoshop 或其他图像编辑器手动计算像素。附:你需要这些信息做什么?也许我们可以帮助解决更广泛的问题。

标签: javascript html-select text-indent


【解决方案1】:

我会尝试根据CSS box model 来确定。在你的情况下,我希望它有一个pading-left。您想要从选择边框到文本内容的空间。这受选择填充、选项边距、选项边框和选项填充的影响。

select = window.getComputedStyle(document.querySelector('select'))
option = window.getComputedStyle(document.querySelector('option'))
console.log(select['padding-left'])
console.log(option['margin-left'])
console.log(option['border-left'])
console.log(option['padding-left'])
<select><option>Item</option><select>

【讨论】:

  • window.getComputedStyle(select.querySelector("option")).paddingLeft 是完美的
【解决方案2】:

你在正确的轨道上

const el = document.querySelector('select');
const computedStyle = getComputedStyle(el);
var indent = computedStyle.textIndent ;
var padding = computedStyle.padding ;
var margin = document.getElementById("myDiv").style.margin;

只需使用查询选择器将它们分配给变量,您可以在页面上拥有多个,因此它会隐藏您要查找的特定变量,因此我更喜欢通过 ID 来调用事物

【讨论】:

    猜你喜欢
    • 2011-09-22
    • 2017-07-28
    • 2020-04-21
    • 1970-01-01
    • 2013-08-06
    • 2020-12-18
    • 2018-02-25
    • 2016-05-18
    • 2011-08-06
    相关资源
    最近更新 更多