大场前端工程师常使用CSS3特性做跨域也是牛逼前端的开始之路

通过 CSS3 的 content 获取内容,很有意思的一个思路,实际场景中有可能用的到:

CSST (CSS Text Transformation)

利用js动态创建一个link插入到文档中, 请求css文件.

利用 computedStyle = window.getComputedStyle 获取指定元素的 style 对象

利用 computedStyle .content 获取内容


服务端可以返回的 css 文件内容:

@keyframes anima {
  from {}
  to {
    opacity: 0;
  }
}
@-webkit-keyframes anima {
  from {}
  to {
    opacity: 0;
  }
}
#CSST {
  content: "${text}";
  animation: anima 2s;
  -webkit-animation: anima 2s;
}

${text}就是我们要填充的数据

监听函数 animationstart/webkitAnimationStart 来判断css是否加载完成

给#CSST元素设置动画

js逻辑:

function handle () {
  var computedStyle = getComputedStyle(span, false);
  var content = computedStyle.content;
  console.log('content: %s', content);
  var match = content.match(/[w+=/]+/);
  // base64解码
  if (match) {
      try {
          content = decodeURIComponent(escape(atob(match[0])));
      } catch (ex) {
          fn(ex);
          return;
      }
  }
  return content
}
var CSST = document.getElementById('CSST');
//监听事件
CSST.addEventListener('animationstart', handler, false);
CSST.addEventListener('webkitAnimationStart', handler, false);

办公资源网址导航 https://www.wode007.com

元素动画启动,就可以获取到 content 里的内容了

原文地址:https://www.cnblogs.com/ypppt/p/12942098.html