CSS边界动画适用于整个Div内容

时间:2016-06-02 21:59:06

标签: html css

我有一个带边框的div,并在其中形成。我决定为边界设置动画,以便它可以发出脉冲。我的代码:

<div class="main">
<div class="border">

-Text Here-

</div>
</div>

我的CSS:

@keyframes pulse {
  0% { opacity: 0;  animation-timing-function: ease-in;}
  20% { opacity: .2; animation-timing-function: ease-in;}
  40% { opacity: .4; animation-timing-function: ease-in;}
  45% { opacity: .8; animation-timing-function: ease-in;}
  50%% { opacity: 1; animation-timing-function: ease-in;}
  50%% { opacity: 1; animation-timing-function: ease-out;}
  55% { opacity: .8; animation-timing-function: ease-out;}
  60% { opacity: .4; animation-timing-function: ease-out;}
  80% { opacity: .2; animation-timing-function: ease-out;}
  100% { opacity: 0; animation-timing-function: ease-out;}
}

.border {
  border-radius: 25px;
  border: 8px solid #2C3E50;
  animation-name: pulse;
  animation-duration: 4s;
  animation-iteration-count: infinite;
}  

.main{
  padding: 50px;
  width: 500px;
  height: 500px;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
}

问题是动画适用于div +边框的整个内容,我希望它只适用于边框而不是内部的内容。我知道这可能很容易解决,但我对CSS不太好。

另外,当用户点击div内的任何地方时,如何动画启动,即使在div外部点击也能保持运行。提前谢谢。

1 个答案:

答案 0 :(得分:2)

使用opacity而不是使用会影响整个div的border-colorFiddle

@keyframes pulse {
        0%   { border-color: rgba(0, 255, 255, 1); }
        50%  { border-color: rgba(0, 255, 255, 0); }
        100% { border-color: rgba(0, 255, 255, 1); }
}

.border {
  border-radius: 25px;
  border: 8px solid #2C3E50;
  animation: pulse 2s infinite;
}  

如果您想切换&amp;当单击特定div时,您可以使用以下函数切换类:

function changeclass() {
   var blah = document.getElementById("border")
   if (blah.className=="border"){
       blah.className = "";
   }
   else{
       blah.className="border";
   }
} 

你的HTML将是:

<div class="main">
<div id="border" onclick="changeclass()">
-Text Here- 
</div>
</div>

如果要在内部单击时切换,然后在页面上的任何位置单击时切换为关闭,则将eventlistener添加到文档中,如下所示:

document.addEventListener('click', function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;   
        if (target.className == "border"){
            target.className = "";
        }
        else{
            document.getElementById("border").className = "border";
        }
}, false);

你的HTML将是:

<div class="main">
<div id="border">
-Text Here-
</div>
</div>

不透明度是rgba中的第4个位置,因此请使用0.0-1.0作为值。不那么透明了。