使用CSS内联JavaScript

Vin*_*hua 0 html javascript css

我想使用内联JavaScript来扭曲列表标记.

这是li它调用的标记和方法:

<li onPageload=
             "myFunction( element.style.webkitTransform = "skew(-25deg)"; ">
</li>
Run Code Online (Sandbox Code Playgroud)

但是,它不起作用.我哪里做错了?

m59*_*m59 5

内联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>
Run Code Online (Sandbox Code Playgroud)

CSS:

/* this class will be added to the elements so this style is applied */
.skewed {
  -webkit-transform: skew(-25deg);    
  transform: skew(-25deg);
}
Run Code Online (Sandbox Code Playgroud)

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';
  }
});
Run Code Online (Sandbox Code Playgroud)

现场演示(点击).

更直接地回答你的问题(我不推荐这种方法!):

<!-- 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>
Run Code Online (Sandbox Code Playgroud)

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; 
}
Run Code Online (Sandbox Code Playgroud)

现场演示(点击).