Jump to content
  • 0

Взять стиль из объекта


user89
 Share

Question

Есть объект, в котором прописаны некоторые CSS-свойства. Хочется применить их к элементу. Делаю так (самое интересное ошибки нет)

<!DOCTYPE html><html><head><meta charset="utf-8"><style>#d1 {width:200px; border:1px solid #ccc; margin:20px;}</style></head><body><button onclick="run(s)" id="Button1">Button1</button><div id="d1">div 1</div><script>var s = {id:'d1', background:'orange', padding:'10px', border:'2px solid green'};function run(s) {  var el = document.getElementById(s.id), k;  for (k in s) {    if (k != 'id') {          console.log('el.style.' + k + ' = ' + '"' + s[k] + '"');      el.style.k = '"' + s[k] + '"';    }  }}</script></body></html>

В консоле выводятся правильные строки

el.style.background = "orange"

el.style.padding = "10px"

el.style.border = "2px solid green"

но я не знаю, как их применить к стилю элемента. Использовать eval() не хочется.

el.style[k] также не помог... Пример на фиддлере https://jsfiddle.net/6ohy1qdy/

 

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0
Решение



<!DOCTYPE html>
<html>
<head>
<title>Взять стиль из объекта</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<style>
#d1 {width:200px; border:1px solid #ccc; margin:20px;}
</style>
</head>

<body>
<button onclick="run(s);">Взять стиль из объекта</button>
<div id="d1">div 1</div>

<script type='text/javascript'>
var s = {
id: 'd1',
style: {
background: 'orange',
padding: '15px',
border: '2px solid green'
}
};
function run(s) {
var el = document.getElementById(s.id);
for (var k in s.style) {
el.style[k] = s.style[k];
};
};
</script>
</body>
</html>

Edited by user89
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy