gpt4 book ai didi

javascript - 如何获取和设置来自类的对象的样式属性?

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:54 25 4
gpt4 key购买 nike

我有一个简单的动画功能,通过改变宽度来模拟按下按钮:

function bPress(b) {
var w = (parseFloat(b.style.width)*0.96);
if (b.style.width.substr(-1)=="%") {
var s ="%";
}
else {
var s = "em";
}
b.style.width = w +s;
b.onmouseup = function () {
w = (parseFloat(b.style.width)/0.96);
b.style.width = w+s;
// etc.
}

在我开始清理我的代码并将内联 CSS 样式声明更改为类之前,它一直运行良好。我以前有,例如:

<div style= 'height: 1.5em; width: 100%; margin: 0 auto; margin-top: 0.2em; font: inherit; font-weight:bold' onclick='checkSave("continue")' onmousedown='bPress(this)'>Continue</div>

我将 CSS 部分移到了一个新类中:

.response_button {
height: 1.5em;
width: 100%;
margin: 0 auto;
margin-top: 0.2em;
font: inherit;
font-weight:bold
}

...避免重复,当然还简化了 div 标签。但是动画停止工作了。经过一些试验,我最终想出了一个临时解决方案,将宽度移回到内联样式声明中。但这似乎是错误的。

所以 2 个问题:

  1. 如果在类中声明宽度,为什么 this.style.width 不起作用?
  2. 如果在类中声明了 div 的属性,是否有办法获取和设置它们?

编辑:为了完整起见,使用 nick zoum 的回答,这里是修改后的 bPress 函数:

function bPress(b) {
var w_px = window.getComputedStyle(b).width;
var w_int = (parseInt(w_px));
b.style.width = Math.round(w_int * 0.96) + "px";
b.onmouseup = function () {
b.style.width = w_px;
}
}

最佳答案

您可以使用 getComputedStyle 获取元素的所有计算样式属性。

var dom = document.querySelector("#foo");

console.log(getComputedStyle(dom).backgroundColor);
#foo {
background-color: red;
width: 10px;
height: 10px;
}
<div id="foo"></div>

关于javascript - 如何获取和设置来自类的对象的样式属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57414912/

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