javascript - div 可以旋转,span 不能旋转但它可以动画转换

标签 javascript html css

我在 html 中附加了三个对象的代码。请查看 SO 代码 Playground 或此处:http://jsfiddle.net/kr34643L/

第一个 (id1) 是一个 div,我可以通过 css3 旋转它。

第二个 (id2) 是一个 span 并且不可能以相同的方式旋转它。

但是可以在进行转换时旋转 span (id3)。只是它不会停留在那个位置。

我看过关于将显示设置为blockinline-block 的答案,但老实说我不明白为什么我必须更改显示样式。特别是当过渡效果很好但最后没有保持位置时。

var id1 = document.getElementById('id1');
var id2 = document.getElementById('id2');
var id3 = document.getElementById('id3');

var rotate1 = 0;
var rotate2 = 0;
var rotate3 = 0;

id1.addEventListener("click", function(){
    rotate1 = rotate1 ? 0 : 45;
    id1.style.transform = "rotate("+rotate1+"deg)";
});

id2.addEventListener("click", function(){
    rotate2 = rotate2 ? 0 : 45;
    id2.style.transform = "rotate(" + rotate2 + "deg)";
});

id3.addEventListener("click", function(){
    rotate3 = rotate3 ? 0 : 45;
    id3.style.transform = "rotate(" + rotate3 + "deg)";
    id3.style.transition = "transform 2s";
});
#id1, #id2, #id3 {
    width: 100px;
    height: 15px;
    border: 2px solid;
}
<div class="centerbox">
  <div id="id1" style="cursor:pointer">div can rotate</div>
  <span id="id2" style="cursor:pointer">span doesn't</span><br>
  <span id="id3" style="cursor:pointer">span can transform though</span>
</div>  

更新

  • 以上说明仅适用于Chrome
  • FireFox 上,id2 和 id3 不旋转,id3 的转换不起作用
  • IE11 上所有旋转和 id3 的转换都有效

最佳答案

实际上,CSS 转换样式不适用于内联元素,因为它们不被视为 block 元素。

来自 W3 standard 的官方答案检查.

根据可变形元素的W3标准:

  • an element whose layout is governed by the CSS box model which is either a block-level or atomic inline-level element, or whose display property computes to table-row, table-row-group, table-header-group, table-footer-group, table-cell, or table-caption [CSS21]

  • an element in the SVG namespace and not governed by the CSS box model which has the attributes transform, ‘patternTransform‘ or gradientTransform [SVG11].

所以你不能将转换样式应用于 <span> 元素。

关于javascript - div 可以旋转,span 不能旋转但它可以动画转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31504419/

相关文章:

javascript - 类型错误 : res is not a function

javascript - 页面刷新javascript后如何保存事件选项卡

html - IE8/Compat View Bug - 所有图像在 Div 顶部相互堆叠。需要帮忙

css - ExtJS 组合框无法正确呈现

javascript - 如何使用 jQuery 将正则表达式应用于输入?

javascript - JQuery/JavaScript - 滚动到附加 div 上的 anchor

javascript - 在页面加载时添加表格的列

javascript - 我可以在发布表单输入时重定向到新的 php 文件吗?

javascript - 动画 SVG,圆形描边悬停

html - 如何使用 div 在底部和顶部部分分割屏幕,其中底部是固定高度,顶部占用剩余空间