문제

I have a situation where, depending on a variable value, I will want to modify EITHER the margin-top OR margin-bottom property of a div.

Apart from using an "if else", is there any way of doing it kinda like this :

var whichmargin="marginTop";
document.getElementById('myElement').style.whichmargin = '100px';

If you get what I mean lol ?

By the way, I am using vanilla JS rather than jQuery.

I don't want to use SetAttribute as I don't want to alter any other of the div style.

Any ideas much appreciated:

도움이 되었습니까?

해결책

using the [] syntax:

var value = 'somethingelse';
var whichmargin = value === 'something' ? "marginTop" : "marginBottom";
document.getElementById('myElement').style[whichmargin] = '100px';
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top