javascript:你会如何使用javascript旋转文本?

时间:2016-08-18 02:53:05

标签: javascript html

我有这段代码:

<img src="http://www.w3schools.com/html/html5.gif" id="imgid">
<h1 id='header'>Example</h1>
<!--This is an example html doc not the real thing!-->
<button onclick="spin(document.getElementById('header'));spin(document.getElementById('imgid'));">Spin!</button>
<script>
  function spin(object) {
    setInterval(function() {
      object.style.transform += "rotate(10deg)";
    }, 1);
  }
</script>

如何正确旋转文字?如果你能解释它是如何工作的话那就太好了。如果您需要我的资料来源,那么:

“正确”是指旋转居中。 (不是全页)。

谢谢!

1 个答案:

答案 0 :(得分:2)

试试这个。主要问题是宽度一直延伸到整个页面,这会使旋转变得混乱,因此添加display:inline-block使得宽度与div的内容相匹配。

<style>
#imgid{display:inline-block;}
#myDIV{display:inline-block;}
</style>

<html>
    <head>
        <title>Example</title>
    </head>

    <body>
        <div><img src="http://www.w3schools.com/html/html5.gif" id="imgid"></div>
        <div><h1 id='myDIV'>Example</h1></div>
        <div><button onclick="spin(document.getElementById('imgid'));spin(document.getElementById('myDIV'));">xdfdsf</button></div>
    </body>
</html>

<script>
function spin(object)
{
    setInterval(function()
    {
        object.style.transform += "rotate(10deg)";
    }, 1);
}
</script>