我想使用内联 JavaScript 倾斜列表标记。
这里是 li
标签和它调用的方法:
<li onPageload=
"myFunction( element.style.webkitTransform = "skew(-25deg)"; ">
</li>
但是,它不起作用。我哪里做错了?
最佳答案
内联 js 从来都不是一个好的做法。阅读其中一些结果:https://www.google.com/search?q=Why+is+inline+js+bad%3F
内联 js 会损害可读性、关注点分离、可维护性,会产生意想不到的结果,正如您在此处看到的那样,编写起来很奇怪。
下面是一个用 js 添加样式的干净解决方案。我在代码中的注释解释了发生了什么。
示例标记:
<ul>
<!-- the class here is just for the example - something to select the elements by -->
<li class="skew-this"></li>
<li class="skew-this"></li>
</ul>
CSS:
/* this class will be added to the elements so this style is applied */
.skewed {
-webkit-transform: skew(-25deg);
transform: skew(-25deg);
}
JavaScript:
//this is the proper way to fire a function on page load
window.addEventListener('load', function() {
//get element references
var lis = document.getElementsByClassName('skew-this');
//loop through the selected elements
for (var i=0; i<lis.length; ++i) {
var li = lis[i];
//add "skewed" to the element's className - now it is styled!
li.className = li.className+' skewed';
}
});
更直接地回答你的问题(我不推荐这种方法!):
<!-- call "loadFunc" on page load -->
<body onload="loadFunc()">
<ul>
<!-- "skew" is the name of the function that will be called for this element on page load -->
<li load="skew"></li>
<li load="skew"></li>
</ul>
</body>
JavaScript:
//this is called when the page is loaded
function loadFunc() {
//get element references that have "load" attribute
var lis = document.querySelectorAll('li[load]');
//loop through elements
for (var i=0; i<lis.length; ++i) {
var li = lis[i];
//get the "load" function name ("skew" in this example)
var func = li.getAttribute('load');
//call the function, passing in the element
window[func](li);
}
}
function skew(elem) {
//skew the element
var val = 'skew(-25deg)';
elem.style['-webkit-transform'] = val;
elem.style.transform = val;
}
关于javascript - 使用 CSS 内联 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21153802/