JavaScript에서 여러 CSS 스타일을 설정하려면 어떻게해야합니까?
다음 JavaScript 변수가 있습니다.
var fontsize = "12px"
var left= "200px"
var top= "100px"
나는 이것을 다음과 같이 반복적으로 내 요소로 설정할 수 있다는 것을 알고있다.
document.getElementById("myElement").style.top=top
document.getElementById("myElement").style.left=left
이 모든 것을 한 번에 하나로 묶을 수 있습니까?
document.getElementById("myElement").style = allMyStyle
CSS 값을 문자열로 가지고 있고 요소에 대해 이미 설정된 다른 CSS가없는 경우 (또는 덮어 쓰지 않아도 됨) cssText
속성 을 사용하십시오 .
document.getElementById("myElement").style.cssText = cssString;
이것은 속성을 변경할 때마다 요소를 다시 칠하지 않기 때문에 의미가 있습니다 (어쨌든 "한 번에 모두"변경).
다른 쪽에서는 먼저 문자열을 작성해야합니다.
Object.assign 사용 :
Object.assign(yourelement.style,{fontsize:"12px",left:"200px",top:"100px"});
또한 CSS 스타일을 다시 쓰는 대신 스타일을 병합 할 수 있습니다.
바로 가기 기능을 만들 수도 있습니다.
const setStylesOnElement = function(styles, element){
Object.assign(element.style, styles);
}
@Mircea : 단일 문장에서 요소에 대한 여러 스타일을 설정하는 것은 매우 쉽습니다. 기존 속성에 영향을 미치지 않으며 루프 또는 플러그인으로 이동하는 복잡성을 피합니다.
document.getElementById("demo").setAttribute(
"style", "font-size: 100px; font-style: italic; color:#ff0000;");
주의 사항 : 나중에이 메소드를 사용하여 스타일 특성을 추가하거나 변경하면 'setAttribute'를 사용하여 설정 한 이전 특성이 지워집니다.
처리하는 기능을 만들고 변경하려는 스타일로 매개 변수를 전달하십시오.
function setStyle( objId, propertyObject )
{
var elem = document.getElementById(objId);
for (var property in propertyObject)
elem.style[property] = propertyObject[property];
}
이렇게 불러
setStyle('myElement', {'fontsize':'12px', 'left':'200px'});
propertyObject 내부의 속성 값에 변수를 사용할 수 있습니다.
JavaScript 라이브러리를 사용하면 이러한 작업을 매우 쉽게 수행 할 수 있습니다
jQuery
$('#myElement').css({
font-size: '12px',
left: '200px',
top: '100px'
});
객체와 for-in-loop
또는 훨씬 더 우아한 방법은 기본 객체 및 for 루프입니다.
var el = document.getElementById('#myElement'),
css = {
font-size: '12px',
left: '200px',
top: '100px'
};
for(i in css){
el.style[i] = css[i];
}
Javascript에서 여러 CSS 스타일 속성 설정
document.getElementById("yourElement").style.cssText = cssString;
또는
document.getElementById("yourElement").setAttribute("style",cssString);
예:
document
.getElementById("demo")
.style
.cssText = "margin-left:100px;background-color:red";
document
.getElementById("demo")
.setAttribute("style","margin-left:100px; background-color:red");
방금 여기에서 우연히 만났는데 왜 이것을 달성하기 위해 너무 많은 코드가 필요한지 알 수 없습니다.
CSS 코드를 문자열로 추가하십시오.
let styles = `
font-size:15em;
color:red;
transform:rotate(20deg)`
document.querySelector('div').style = styles
<div>a</div>
CSS 파일에 개별 클래스를 가지고 클래스 이름을 요소에 할당 할 수 있습니다
또는 스타일 속성을 다음과 같이 반복 할 수 있습니다.
var css = { "font-size": "12px", "left": "200px", "top": "100px" };
for(var prop in css) {
document.getElementById("myId").style[prop] = css[prop];
}
그것이 가능하다고 생각하지 마십시오.
그러나 스타일 정의에서 오브젝트를 작성하고 반복 할 수 있습니다.
var allMyStyle = {
fontsize: '12px',
left: '200px',
top: '100px'
};
for (i in allMyStyle)
document.getElementById("myElement").style[i] = allMyStyle[i];
더 발전하려면 기능을 만드십시오.
function setStyles(element, styles) {
for (i in styles)
element.style[i] = styles[i];
}
setStyles(document.getElementById("myElement"), allMyStyle);
일반 자바 스크립트를 사용하면 모든 스타일을 한 번에 설정할 수는 없습니다. 당신은 그들 각각에 대해 한 줄을 사용해야합니다.
그러나 document.getElementById(...).style.
코드 를 반복해서 반복 할 필요는 없습니다 . 이를 참조 할 객체 변수를 작성하면 코드를 훨씬 더 읽기 쉽게 만들 수 있습니다.
var obj=document.getElementById("myElement").style;
obj.top=top;
obj.left=left;
...기타. 예제보다 훨씬 쉽게 읽을 수 있습니다 (솔직히 jQuery 대안만큼 읽기 쉽습니다).
(if Javascript had been designed properly, you could also have used the with
keyword, but that's best left alone, as it can cause some nasty namespace issues)
Your best bet may be to create a function that sets styles on your own:
var setStyle = function(p_elem, p_styles)
{
var s;
for (s in p_styles)
{
p_elem.style[s] = p_styles[s];
}
}
setStyle(myDiv, {'color': '#F00', 'backgroundColor': '#000'});
setStyle(myDiv, {'color': mycolorvar, 'backgroundColor': mybgvar});
Note that you will still have to use the javascript-compatible property names (hence backgroundColor
)
See for .. in
Example:
var myStyle = {};
myStyle.fontsize = "12px";
myStyle.left= "200px";
myStyle.top= "100px";
var elem = document.getElementById("myElement");
var elemStyle = elem.style;
for(var prop in myStyle) {
elemStyle[prop] = myStyle[prop];
}
This is old thread, so I figured for anyone looking for a modern answer, I would suggest using Object.keys();
var myDiv = document.getElementById("myDiv");
var css = {
"font-size": "14px",
"color": "#447",
"font-family": "Arial",
"text-decoration": "underline"
};
function applyInlineStyles(obj) {
var result = "";
Object.keys(obj).forEach(function (prop) {
result += prop + ": " + obj[prop] + "; ";
});
return result;
}
myDiv.style = applyInlineStyles(css);
There are scenarios where using CSS alongside javascript might make more sense with such a problem. Take a look at the following code:
document.getElementById("myElement").classList.add("newStyle");
document.getElementById("myElement").classList.remove("newStyle");
This simply switches between CSS classes and solves so many problems related with overriding styles. It even makes your code more tidy.
With Zam you would do it like this
zam.css({'font-size':'12px','left':'200px','top':'100px'}, '#myElement');
You can write a function that will set declarations individually in order not to overwrite any existing declarations that you don't supply. Let's say you have this object parameter list of declarations:
const myStyles = {
'background-color': 'magenta',
'border': '10px dotted cyan',
'border-radius': '5px',
'box-sizing': 'border-box',
'color': 'yellow',
'display': 'inline-block',
'font-family': 'monospace',
'font-size': '20px',
'margin': '1em',
'padding': '1em'
};
You might write a function that looks like this:
function applyStyles (el, styles) {
for (const prop in styles) {
el.style.setProperty(prop, styles[prop]);
}
};
which takes an element
and an object
property list of style declarations to apply to that object. Here's a usage example:
const p = document.createElement('p');
p.textContent = 'This is a paragraph.';
document.body.appendChild(p);
applyStyles(p, myStyles);
applyStyles(document.body, {'background-color': 'grey'});
// styles to apply
const myStyles = {
'background-color': 'magenta',
'border': '10px dotted cyan',
'border-radius': '5px',
'box-sizing': 'border-box',
'color': 'yellow',
'display': 'inline-block',
'font-family': 'monospace',
'font-size': '20px',
'margin': '1em',
'padding': '1em'
};
function applyStyles (el, styles) {
for (const prop in styles) {
el.style.setProperty(prop, styles[prop]);
}
};
// create example paragraph and append it to the page body
const p = document.createElement('p');
p.textContent = 'This is a paragraph.';
document.body.appendChild(p);
// when the paragraph is clicked, call the function, providing the
// paragraph and myStyles object as arguments
p.onclick = (ev) => {
applyStyles(p, myStyles);
}
// this time, target the page body and supply an object literal
applyStyles(document.body, {'background-color': 'grey'});
I think is this a very simple way with regards to all solutions above:
const elm = document.getElementById("myElement")
const allMyStyle = [
{ prop: "position", value: "fixed" },
{ prop: "boxSizing", value: "border-box" },
{ prop: "opacity", value: 0.9 },
{ prop: "zIndex", value: 1000 },
];
allMyStyle.forEach(({ prop, value }) => {
elm.style[prop] = value;
});
참고URL : https://stackoverflow.com/questions/3968593/how-can-i-set-multiple-css-styles-in-javascript
'Programming' 카테고리의 다른 글
잔가지 템플릿으로 현재 URL을 얻으시겠습니까? (0) | 2020.06.08 |
---|---|
파이썬에서 for 루프의 첫 번째 항목을 건너 뛰시겠습니까? (0) | 2020.06.08 |
자동 레이아웃을 사용하여 텍스트로 확장되는 UITextView (0) | 2020.06.08 |
PHP는 나이를 계산 (0) | 2020.06.08 |
모든 줄의 끝에 텍스트를 붙여 넣는 방법? (0) | 2020.06.08 |