JavaScript中浏览器兼容问题的写法小议

来源:互联网 发布:淘宝发货无需物流 编辑:程序博客网 时间:2024/05/22 08:17

  • 前言
  • window窗口大小
  • 获取内部样式表和外部样式表
  • onscroll事件
  • 事件对象

前言

  • JavaScript中很多坑,其中对浏览器的兼容也是一个问题,本文就简略的归纳了部分针对浏览器兼容问题的写法的例子,旨在便于查找。如果读者有什么好的意见建议,请留言交流,谢谢!

window窗口大小

  • 1.在IE9+、Chrome、Firefox、Opera以及Safari中
    • window.innerHeight获取浏览器窗口的内部高度
    • window.innerWidth获取浏览器窗口的内部宽度
var msg = "窗口宽度:" + window.innerHeight + "\n窗口高度:" + window.innerWidth;alert(msg );
  • 2.在IE5/6/7/8(Chrome和Firefox也支持)
    • document.documentElement.clientHeight
    • document.documentElement.clientWidth
var msg = "窗口宽度:" + document.documentElement.clientWidth + "\n窗口高度:" + document.documentElement.clientHeight;alert(msg);
  • 3.兼容写法(可以涵盖所有的浏览器)
    • 就是把前两者的写法相 “或”。
var w = window.innerWidth || document.documentElement.clientWidth;var h = window.innerHeight || document.documentElement.clientHeight;alert("窗口宽度:" + w + "\n窗口高度:" + h);

获取内部样式表和外部样式表

  • 1.对IE浏览器:对象.currentStyle[“属性名”]
  • 2.其他浏览器:window.getComputedStyle(对象, null)[“属性名”]
  • 注意:内部样式表中的属性和外部样式表中的属性只能获取不能修改。如果想修改需要通过行间样式表修改,行间样式表的优先级最高,会覆盖内部样式表和外部样式表。
  • 为了简化书写和兼容浏览器,一般封装一个方法。如下列。
<body>    <div id="box1"></div>    <script type="text/javascript">        var box1 = document.getElementById("box1");        // alert(box1.currentStyle["width"]); //只支持IE浏览器        // alert(window.getComputedStyle(box1, null)["height"]); //支持浏览器外的其他浏览器        alert(getStyle(box1, "backgroundColor"));        /*            为了简化书写和兼容浏览器,一般封装一个方法出来        */        function getStyle (obj, attributeName) {                if(obj.currentStyle){   //如果存在对象,则是在ie浏览器                return obj.currentStyle[attributeName];            }else { //其他浏览器                return window.getComputedStyle(obj, null)[attributeName];            }        }    </script></body>

onscroll事件

<script type="text/javascript">     window.onscroll = function () {        console.log("开始滚动...");        //跨浏览器获得滚动的距离        console.log(document.documentElement.scrollTop | document.body.scrollTop);    }</script>

事件对象

box.onclick = function(event) {            event = event || window.event;            console.log("offsetX:" + event.offsetX + " offsetY:" + event.offsetY);            console.log("screenX:" + event.screenX + " screenY:" + event.screenY);            console.log("clientX:" + event.clientX + " clientY:" + event.clientY);            console.log("pageX:" + event.pageX + " pageY: " + event.pageY);}
0 0
原创粉丝点击