Skip to content

Instantly share code, notes, and snippets.

@jxinging
Created April 1, 2016 05:08
Show Gist options
  • Save jxinging/8f37490b5fef92deddea38f7f831ef13 to your computer and use it in GitHub Desktop.
Save jxinging/8f37490b5fef92deddea38f7f831ef13 to your computer and use it in GitHub Desktop.
字符下落效果
$(function(){
function getElementLeft(element){
  var actualLeft = element.offsetLeft;
  var current = element.offsetParent;
  while (current !== null){
    actualLeft += current.offsetLeft;
    current = current.offsetParent;
  }
  return actualLeft;
}
function getElementTop(element){
  var actualTop = element.offsetTop;
  var current = element.offsetParent;
  while (current !== null){
    actualTop += current.offsetTop;
    current = current.offsetParent;
  }
  return actualTop;
}
function getElementViewLeft(element){
  return getElementLeft(element) - document.body.scrollLeft;
}
function getElementViewTop(element){
  return getElementTop(element) - document.body.scrollTop;
}
// 遍历所有dom节点, 给文本字符加上 <span clss="xxx">char</span>
function walkChildren($children){
$children.each(function(){
var $this = $(this);
var $myChildren = $this.children(':not(script)');
if($myChildren.length){
walkChildren($myChildren);
}else{
var text = $.trim($this.text());
if(text.length){
var $elem = $this;
var text = $elem.text();
var span_text = [];
for(var i=0; i<text.length; i++){
var char = text[i];
if(char == ' ' || char == '\n'){
continue;
}
span_text.push("<span class='april_1st_joke'>"+char+"</span>");
}
span_text = span_text.join("");
$elem.html(span_text);
}
}
});
}
walkChildren($("body").children(':not(script)'));
$("img,.fa,.glyphicon").addClass('april_1st_joke');
$(".april_1st_joke").mouseover(function(){
var $this = $(this);
// 当去掉 april_1st_joke class 后不再有效果
if(!$this.hasClass('april_1st_joke')){
return;
}
var hasFixedParent = $this.parents().filter(function(){
if($(this).css('position') === 'fixed'){
return true;
}
}).length;
if(hasFixedParent){
var top = getElementTop(this);
}else{
var top = getElementViewTop(this);
}
var left = getElementViewLeft(this);
var clone = $this.clone();
clone.addClass('falling-it').css({
'position': 'fixed',
'z-index': '999999999',
'top': top+'px',
'left': left+'px',
});
$this.css('visibility', 'hidden').after(clone);
clone.animate({
'top': screen.height*2,
}, (screen.height-top)*4);
});
function resetFallingJoke(){
$(".april_1st_joke").css('visibility',
'visible').removeClass('april_1st_joke');
$(".falling-it").remove();
}
$('body').click(function(){
resetFallingJoke();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment