为什么自定义CSS样式赋值函数无法接收prop参数值?
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 thepropvariable (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 setselement.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

