今天遇到一个奇葩的需求,统计一个iframe里面的页面被点击的量。统计是用第三方软件cnzz站长统计的。想法就是点击动态添加cnzz,但是iframe没法添加点击事件。这就尴尬了。网上一顿搜索。。。。
发现了 document.activeElement属性 :始终会引用DOM中当前获得了焦点的元素。
特点:默认情况下,文档刚刚加载完成的时候,document.activeelement中保存的是document.body元素的引用。文档加载期间,document.activeelement的值为null。通过document.activeelement可以判断文档是否加载完成。
利用 document.activeElement
- var IframeOnClick = {
- resolution: 200,
- iframes: [],
- interval: null,
- Iframe: function() {
- this.element = arguments[0];
- this.cb = arguments[1];
- this.hasTracked = false;
- },
- track: function(element, cb) {
- this.iframes.push(new this.Iframe(element, cb));
- if (!this.interval) {
- var _this = this;
- this.interval = setInterval(function() { _this.checkClick(); }, this.resolution);
- }
- },
- checkClick: function() {
- if (document.activeElement) {
- var activeElement = document.activeElement;
- for (var i in this.iframes) {
- if (activeElement === this.iframes[i].element) { // user is in this Iframe
- if (this.iframes[i].hasTracked == false) {
- this.iframes[i].cb.apply(window, []);
- this.iframes[i].hasTracked = true;
- }
- } else {
- this.iframes[i].hasTracked = false;
- }
- }
- }
- }
- };
- IframeOnClick.track(document.getElementById("iFrame"), function() { alert('a click'); });
此段代码只能执行一次,然后又是一顿操作.....
//html
- <iframe src="http://image.teapaopao.com/just/20170524/01/FJTAYD.html" width="100%" height="100%" scrolling="no" frameborder="0" id="iFrame"></iframe>
- <input type="text" id="btn" style="width: 0; height: 0;position: absolute; left: -100000">
// javascript
- <script>
- var IframeOnClick = {
- resolution: 200,
- iframes: [],
- interval: null,
- Iframe: function () {
- this.element = arguments[0];
- this.cb = arguments[1];
- },
- track: function (element, cb) {
- this.iframes.push(new this.Iframe(element, cb));
- var _this = this;
- this.interval = setInterval(function () {
- _this.checkClick();
- }, this.resolution);
- },
- checkClick: function () {
- if (document.activeElement) {
- var activeElement = document.activeElement;
- for (var i in this.iframes) {
- if (activeElement === this.iframes[i].element) { // user is in this Iframe
- this.iframes[i].cb.apply(window, []);
- var btn = document.getElementById("btn")
- btn.focus()
- }
- }
- }
- }
- };
- IframeOnClick.track(document.getElementById("iFrame"), function () {
- console.log(11111);
- });
- </script>
终于实现了 每点击一次就输入一次~~~