Question:
There is an element:
let element = document.getElementById('id')
I can change its left
css property like this:
let left = ...
highlight.style.left = left + 'px';
Is there an analogue to this, just without the need to write 'px'
?
For example, using jquery you can do this:
$(element).css('left', left);
Is it possible without jquery (and without 'px'
)?
Answer:
Yes. No. No.
Well, okay, yes, to the last question:
var $ = (function () {
var allowNumber = ['lineHeight', 'zIndex'];
function $(el) {
if (this instanceof $) {
this.el = el;
} else {
return new $(el);
}
}
$.prototype.css = function css(key, value) {
key = key.replace(/-(\w)/g, function (m, ch) { return ch.toUpperCase() });
if (+value == value && allowNumber.indexOf(key) === -1) {
value += 'px';
}
this.el.style[key] = value;
return this;
}
return $;
})();
$(document.querySelector("div")).css('left', 100).css('line-height', 3);
div {
position: absolute;
left: 0;
top: 0;
background: silver;
}
<div>123</div>
PS: Pixels are evil.