itsource

JavaScript에서 여러 CSS 스타일을 설정하려면 어떻게 해야 합니까?

mycopycode 2022. 9. 14. 22:26
반응형

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가 아직 설정되어 있지 않은 경우(또는 덮어쓰기에 관심이 없는 경우) 속성을 사용합니다.

document.getElementById("myElement").style.cssText = "display: block; position: absolute";

템플릿 리터럴을 사용하면 CSS와 같은 구문을 쉽고 쉽게 읽을 수 있습니다.

document.getElementById("myElement").style.cssText = `
  display: block; 
  position: absolute;
`;

이것은 속성을 변경할 때마다 요소를 다시 칠하지 않기 때문에 어떤 의미에서는 좋습니다(어떻게든 "한 번에" 변경할 수 있습니다).

다른 쪽에서는 먼저 줄을 만들어야 합니다.

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 내의 속성 값에는 변수를 사용할 수 있습니다.

우연히 여기 들어왔는데 왜 이렇게 많은 코드가 필요한지 모르겠어요.

문자열 보간을 사용하여 CSS 코드를 추가합니다.

let styles = `
    font-size:15em;
    color:red;
    transform:rotate(20deg)`

document.querySelector('*').style = styles
a

JavaScript 라이브러리를 사용하면 이러한 작업을 매우 쉽게 수행할 수 있습니다.

j쿼리

$('#myElement').css({
  font-size: '12px',
  left: '200px',
  top: '100px'
});

오브젝트 및 for-in-loop

또는 훨씬 더 우아한 방법은 기본 객체 및 for-loop입니다.

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");

저에게 가장 간단한 방법은 끈/템플릿을 사용하는 것이었습니다.

elementName.style.cssText = `
                                width:80%;
                                margin: 2vh auto;
                                background-color: rgba(5,5,5,0.9);
                                box-shadow: 15px 15px 200px black; `;

여러 줄의 줄을 사용할 수 있기 때문에 편리한 옵션입니다.

스트링 / 리터럴 체크는 이쪽 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

타이프 스크립트에 강하게 입력:

object.assign 방법은 훌륭하지만, 타이프 스크립트를 사용하면 다음과 같이 자동 완성됩니다.

    const newStyle: Partial<CSSStyleDeclaration> =
    { 
        placeSelf: 'centered centered',
        margin: '2em',
        border: '2px solid hotpink'
    };

    Object.assign(element.style, newStyle);

속성 이름은 대시가 없는 camelCase입니다.

이것은 심지어 그들이 언제 추천되지 않는지 알려줄 것이다.

css 파일에 개별 클래스를 가진 후 요소에 클래스 이름을 할당할 수 있습니다.

또는 스타일의 속성을 다음과 같이 반복할 수 있습니다.

var css = { "font-size": "12px", "left": "200px", "top": "100px" };

for(var prop in css) {
  document.getElementById("myId").style[prop] = css[prop];
}

플레인 Javascript를 사용하면 한 번에 모든 스타일을 설정할 수 없으며, 각 스타일에 한 줄씩 사용해야 합니다.

이렇게 '아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아,document.getElementById(...).style.코드 반복: 참조할 개체 변수를 만들면 코드를 훨씬 더 쉽게 읽을 수 있습니다.

var obj=document.getElementById("myElement").style;
obj.top=top;
obj.left=left;

...등. 당신의 예보다 훨씬 읽기 쉽다(솔직히 jQuery의 대체 예와 마찬가지로 읽기 쉽다).

되었다면 (Javascript)를 입니다.with키워드입니다만, 네임스페이스에 문제가 생길 수 있기 때문에, 이 키워드는 그대로 두는 것이 좋습니다.)

그것이 가능하다고 생각하지 마세요.

그러나 스타일 정의에서 객체를 생성하여 루핑할 수 있습니다.

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);

스타일을 직접 설정하는 기능을 만드는 것이 가장 좋습니다.

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});

되는 속성 이름 javascript)을 .backgroundColor)

CSSStyleDeclaration.setProperty() Object.entries스타일 오브젝트.
이것을 속성의.
CSS를 사용하다

const styles = {
  "font-size": "18px",
  "font-weight": "bold",
  "background-color": "lightgrey",
  color: "red",
  "padding": "10px !important",
  margin: "20px",
  width: "100px !important",
  border: "1px solid blue"
};

const elem = document.getElementById("my_div");

Object.entries(styles).forEach(([prop, val]) => {
  const [value, pri = ""] = val.split("!");
  elem.style.setProperty(prop, value, pri);
});
<div id="my_div"> Hello </div>

문자열은 추가를 지원하므로 현재 스타일을 재정의하지 않고 쉽게 추가할 수 있습니다.

document.getElementById("myElement").style.cssText += `
   font-size: 12px;
   left: 200px;
   top: 100px;
`;

대해서는, 을 참조해 주세요.

예:

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];
}

오래된 스레드이기 때문에 최신 답변을 찾고 계신 분은 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);

이러한 문제에 대해 javascript와 함께 CSS를 사용하는 것이 더 타당할 수 있는 시나리오가 있습니다.다음 코드를 확인합니다.

document.getElementById("myElement").classList.add("newStyle");
document.getElementById("myElement").classList.remove("newStyle");

이것은 단순히 CSS 클래스를 전환하고 덮어쓰기 스타일에 관련된 많은 문제를 해결합니다.코드를 더 깔끔하게 만들 수도 있습니다.

오래된 질문이지만, 이전에 선언한 스타일을 덮어쓰고 싶지 않은 분들을 위해 기능을 사용할 가치가 있다고 생각했습니다.아래 함수는 Object.assign을 사용하여 스타일을 적절하게 수정합니다.내가 한 일은 이렇다.

function cssFormat(cssText){

   let cssObj = cssText.split(";");
   let css = {};
   
   cssObj.forEach( style => {

       prop = style.split(":");

       if(prop.length == 2){
           css[prop[0]].trim() = prop[1].trim();
       } 

   }) 
   
  return css;
}

이제 당신은 다음과 같은 것을 할 수 있다.

let mycssText = "background-color:red; color:white;";
let element = document.querySelector("body");

Object.assign(element.style, cssFormat(mycssText));

요소 선택기와 텍스트를 함수에 모두 입력하면 이 작업을 쉽게 수행할 수 있습니다. 그러면 매번 Object.assign을 사용할 필요가 없습니다.예를들면

function cssFormat(selector, cssText){
  
   let cssObj = cssText.split(";");
   let css = {};
   
   cssObj.forEach( style => {

       prop = style.split(":");

       if(prop.length == 2){
           css[prop[0]].trim() = prop[1].trim();
       } 

   }) 

   element = document.querySelector(selector);
   
   Object.assign(element.style, css); // css, from previous code

} 

다음 작업을 수행할 수 있습니다.

cssFormat('body', 'background-color: red; color:white;') ;

//or same as above (another sample) 
cssFormat('body', 'backgroundColor: red; color:white;') ; 

참고: 문서 또는 대상 요소(예: 본문)가 이미 로드되었는지 확인한 후 선택하십시오.

제공하지 않는 기존 선언을 덮어쓰지 않도록 선언을 개별적으로 설정하는 함수를 작성할 수 있습니다.선언의 오브젝트 파라미터 리스트가 있다고 합니다.

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]);
  }
};

에는 「」이 합니다.element ★★★object해당 개체에 적용할 스타일 선언의 속성 리스트.하다

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'});

위의 모든 솔루션에 대해 이것은 매우 간단한 방법이라고 생각합니다.

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;
});

아래 innerHtml이 유효한가?

var styleElement = win.document.createElement("STYLE");
styleElement.innerHTML = "#notEditableVatDisplay {display:inline-flex} #editableVatInput,.print-section,i.fa.fa-sort.click-sortable{display : none !important}";

ES6+에서는 backticks를 사용하여 css를 다른 곳에서 직접 복사할 수도 있습니다.

const $div = document.createElement('div')
$div.innerText = 'HELLO'
$div.style.cssText = `
    background-color: rgb(26, 188, 156);
    width: 100px;
    height: 30px;
    border-radius: 7px;
    text-align: center;
    padding-top: 10px;
    font-weight: bold;
`

document.body.append($div)

스타일 클래스 추가에 CSS 사용을 검토하고 JavaScript classList & simply add() 함수를 사용하여 이 클래스를 추가해 주세요.

style.css

.nice-style { 
fontsize : 12px; 
left: 200px;
top: 100px;
}

스크립트 JavaScript

const addStyle = document.getElementById("myElement"); addStyle.classList.add('nice-style');

<button onclick="hello()">Click!</button>

<p id="demo" style="background: black; color: aliceblue;">
  hello!!!
</p>

<script>
  function hello()
  {
    (document.getElementById("demo").style.cssText =
      "font-size: 40px; background: #f00; text-align: center;")
  }
</script>

노드 프로토타입에 스타일 함수를 추가할 수 있습니다.

Node.prototype.styles=function(obj){ for (var k in obj)    this.style[k] = obj[k];}

다음으로 임의의 노드의 콜스타일 메서드를 간단하게 호출합니다.

elem.styles({display:'block', zIndex:10, transitionDuration:'1s', left:0});

다른 모든 기존 스타일을 유지하고 객체 매개변수에 있는 값을 덮어씁니다.

이를 위한 다양한 방법:

1. document.getElementById("ID").style.cssText = "display:block; position:relative; font-size:50px";
2. var styles = {"display":"block"; "position":"relative"; "font-size":"50px"};
 
   var obj = document.getElementById("ID");
   Object.assign(obj.style, styles);

3. var obj = document.getElementById("ID");
obj.setAttribute("style", "display:block; position:relative; font-size:50px");

이것이 도움이 되기를 바랍니다~ RDaksh

var styles = {
    "background-color": "lightgray",
    "width": "500px",
    "height": "300px"
};

/

var obj = document.getElementById("container");
Object.assign(obj.style, styles);

언급URL : https://stackoverflow.com/questions/3968593/how-can-i-set-multiple-css-styles-in-javascript

반응형