如何使用JQuery在悬停时动画背景图像?

时间:2017-02-06 09:29:05

标签: jquery css jquery-animate

我有一个方形div,背景为对角线。

当我将鼠标悬停在div上时,我希望对角背景图像展开,如下所示。

enter image description here

我使用了CSS to accomplish this,但我希望转换为动画而不是“捕捉”。

<div class="content-box medium-box corner">
   <div>
   </div>
</div>

* { 
  margin: 0; 
  padding: 0; -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;}

.content-box {
  height: 250px;
  width: 250px;
  padding: 20px;
  margin-bottom: 25px;
  border: 1px solid #000;
  background: url(http://keithdonegan.com/wp-content/uploads/2017/02/corner-bg.svg) 0px 0px;
  background-size: cover;
  transition: all .8s;
}

.content-box:hover {
   background-size: 550px 550px;
   background-position: 0px 0px;
}

当光标离开div时,我也想像背景图像一样动画回原始位置。

Link to the test site

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

这是问题中描述的问题的纯CSS解决方案。

请注意,如果您必须使用背景图像,则可以将其分配给::before元素,并且仍然可以使用相同的CSS进行动画处理,而无需使用js / jQuery ......

作为最佳做法,请始终尽量保持HTML尽可能干净(不需要为动画添加冗余元素......),并尽量避免加载不需要的资源(图像,脚本)。它将使您的页面更快,并且您的代码更容易维护。

&#13;
&#13;
#frame {
  position: relative;
  width: 100px;
  height: 100px;
  margin: 50px auto;
  border: solid 1px red;
  overflow: hidden;
}

#frame::before {
  content: "";
  position: absolute;
  top: 0px;
  left: -100px;
  width:100px;
  height:0;
  border-color: black;
  border-top: solid 100px black;
  border-right: solid 100px transparent;
  border-bottom: none;
  border-left: none;
  transition: left 1s;
}

#frame:hover::before {
  left: 0px;
}
&#13;
<div id="frame"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用纯CSS进行过渡动画。

如果你的情况有可能我会需要你的代码。

但请查看this了解详情。

编辑:使用

background-size: 250px 250px;

而不是封面,maigc已完成

<强> EDIT2:

.content-box {
  height: 250px;
  width: 250px;
  padding: 20px;
  margin-bottom: 25px;
  border: 1px solid #000;
  background: url(http://keithdonegan.com/wp-content/uploads/2017/02/corner-bg.svg) 0px 0px;
  background-size: 250px 250px;
  transition: all 5s;
}

.content-box:hover {
   background-size: 550px 550px;
   background-position: 0px 0px;
   transition: all 5s;
}

答案 2 :(得分:0)

如果您为动画添加中心和缓动,那很好。请尝试:

&#13;
&#13;
* { 
  margin: 0; 
  padding: 0; -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;}

.content-box {
  height: 250px;
  width: 250px;
  padding: 20px;
  margin-bottom: 25px;
  border: 1px solid #000;
  background: url(http://keithdonegan.com/wp-content/uploads/2017/02/corner-bg.svg) 0px 0px;
  background-size: cover;
  background-position: center center;
  padding: 15px;
  position: relative;
  -webkit-transition:  all 0.8s ease 0s;
  transition:  all 0.8s ease 0s;
}

.content-box:hover {
   background-size: 350% 350%;
   background-position: 0px 0px;
}
&#13;
<div class="content-box medium-box corner">
   <div>
   </div>
</div>
&#13;
&#13;
&#13;