javascript改变身体的线条高度

meh*_*dok 5 html javascript css

我有一个改变lineHeight身体的功能(我需要改变所有元素的行高):

if (document.body.style.lineHeight == "")
{ 
    document.body.style.lineHeight = "1.0em";
}
document.body.style.lineHeight = parseFloat(document.body.style.lineHeight) + (0.4) + "em";
Run Code Online (Sandbox Code Playgroud)

如果文档中没有任何line-heightcss,则此代码可以正常工作,并且元素的所有行高都会增加,但在某些情况下会出现奇怪的行为:

1)document.body.style.lineHeight == ""即使身体在css中也是如此line-height!

2)如果line-heightCSS中有任何元素,则此代码将无法更改行高.我可以获得document.body.style.lineHeight价值,我可以看到它增加但是文档中没有任何变化!(没有视觉效果)

任何帮助,将不胜感激.

Sig*_*uza 3

正如评论中已经提到的,您需要window.getComputedStyle()(或只是getComputedStyle())检索元素实际应用的样式,因为element.style只会返回 HTMLstyle属性的内容。

但请注意,这不会是您分配给它的文字值(如1.5em),而是以像素为单位的等效值(1em = 16px顺便说一下)。返回的值也不是数字,而是包含后缀 的字符串px

另请注意,默认值不是"",而是"normal"
但它也可能是"initial"or "inherit",所以我建议不检查其实际值,而只检查字符串是否以px.

所以你的代码可能应该是这样的:

var style = getComputedStyle(document.body);
if (style.lineHeight.match(/px$/) === null)
{ 
    document.body.style.lineHeight = "1.0em";
}
else
{
    document.body.style.lineHeight = (parseFloat(style.lineHeight) / 16) + (0.4) + "em";
}
Run Code Online (Sandbox Code Playgroud)

另:小提琴

最后,请注意,如果您指定百分比作为行高,则无法检索该值(当然除了解析$('style').innerHTML自己之外),您只能在函数运行时获得等效的像素。


至于你的问题如何将行高应用于所有元素,只需<style>在 head 中注入一个标签,其中包含 CSS,如下所示:

*
{
    line-height: 1.0em !important;
}
Run Code Online (Sandbox Code Playgroud)

所以上面的代码片段看起来像这样:

var tag = document.createElement('style');
var style = getComputedStyle(document.body);
if (style.lineHeight.match(/px$/) === null)
{
    tag.innerHTML = '* { line-height: 1.0em !important; }';
}
else
{
    tag.innerHTML = '* { line-height: ' + (parseFloat(style.lineHeight) / 16 + 0.4) + 'em !important; }';
}
document.head.appendChild(tag);
Run Code Online (Sandbox Code Playgroud)

当然,如果已经有更具体的选择器,这将不起作用!important,但否则它甚至会覆盖内联样式属性。

请参阅更新的小提琴