javascript - CSS3 过渡与 Javascript

标签 javascript html css

我有这个网页,鼠标悬停在该网页上时,元素会旋转并在鼠标移出时返回到原始位置。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css"> 
div
{
width:100px;
height:100px;
background:red;
transition:width 2s;
-moz-transition:width 2s; /* Firefox 4 */
-webkit-transition:width 2s; /* Safari and Chrome */
-o-transition:width 2s; /* Opera */
}

div:hover
{
width:300px;
}
</style>
</head>
<body>

<p><b>Note:</b> This example does not work in Internet Explorer.</p>

<div></div>

<p>Hover over the div element above, to see the transition effect.</p>

</body>
</html>  

现在是否可以使用 JavaScript 而不是默认的悬停功能来触发此转换。我尝试创建两个不同的类名,但它只是起作用,即使我通过添加延迟和更改类来做到这一点。有没有办法用 Javascript 做这样的转换??

最佳答案

我相信您需要做的就是在特定事件发生时更改要修改的元素的样式。另外,我更改了 DOCTYPE 以使用 HTML5。试一试:

<!DOCTYPE HTML>
<html>
<head>
<style type="text/css"> 
div.sample1
{
width:100px;
height:100px;
background:red;
transition:width 2s;
-moz-transition:width 2s; /* Firefox 4 */
-webkit-transition:width 2s; /* Safari and Chrome */
-o-transition:width 2s; /* Opera */
}

div.sample1:hover
{
width:300px;
}


</style>
<script type="text/javascript">
function doStuff(obj,boolStateChange)
{
    console.log('test');
    if (boolStateChange==true)
    {
    obj.style.cssText = "width:300px;height:100px;background:green;transition:width 2s;-moz-transition:width 2s;-webkit-transition:width 2s;-o-transition:width 2s;";

    }
    else
    {
    obj.style.cssText = "width:100px;height:100px;background:green;transition:width 2s;-moz-transition:width 2s;-webkit-transition:width 2s;-o-transition:width 2s;";
    }

}
</script>
</head>
<body>

<p><b>Note:</b> This example does not work in Internet Explorer.</p>

<div class="sample1"></div>

<p>Hover over the div element above, to see the transition effect.</p>

<br/><br/><br/>

<div id="javaHover" style="background-color:green;width:100px;height:100px;" onMouseOver="doStuff(this,true);" onMouseOut="doStuff(this,false);"></div>

<p>Hover over the div element above, to see the Javascript transition effect.</p>

</body>
</html>

关于javascript - CSS3 过渡与 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6193756/

相关文章:

javascript - 在 Vue 中,将多个按钮之一更改为单击时处于事件状态

javascript - 具有嵌套私有(private)路由的私有(private)组件

javascript - NodeJS 虚拟机用例

html - CSS3 - 使用 :focus issue 显示工具提示

java - JLabel HTML 呈现的奇怪问题

javascript - jquery 慢慢追加 span

javascript - jquery - 禁用具有动态名称的按钮和输入

html - <p> 标签不接受 CSS 类或 ID

css - Modernizr 测试是否包含以浏览器为前缀的功能?

html - 调整字符串长度