You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么自定义CSS样式赋值函数无法接收prop参数值?

Fixing Your Dynamic CSS Style Function

Hey there! Let's get this sorted out. The issue with your function is how you're trying to use the prop parameter to set the style property.

What's Going Wrong?

When you write element.style.prop, JavaScript treats prop as a literal property name (like trying to set element.style.prop instead of element.style.top). It doesn't recognize that prop is a variable holding the actual property name you want to target.

The Fix: Use Bracket Notation

To dynamically access a property using a variable, you need to use square bracket notation instead of dot notation. Here's the corrected code:

<div id="obj"></div>
<script>
let obj = document.getElementById('obj');
const animate = (element, prop, value) => {
  element.style[prop] = value + 'px';
};
animate(obj, 'top', 100);
</script>

Why This Works

  • element.style[prop] tells JavaScript to take the value of the prop variable (in your case, 'top') and use that as the name of the style property to set.
  • This way, when you pass 'top' as the second argument, it correctly sets element.style.top = '100px'.

Extra Tip

You might also want to add a quick check to make sure the element exists and the property is a valid CSS style property, but for your current use case, the above fix will resolve the core issue.

内容的提问来源于stack exchange,提问作者rahul_plfoams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 06:31:38