• 关于Dom部分操作各浏览器兼容(setAttribute 与添加事件)


    之前项目中有个小功能,我实现了一下,但是在实现中遇到一些问题,今天来谈谈。

    老生常谈的浏览器不兼容,以前只关心css层面的,javascript的dom操作什么的倒是很少关心。如下图,这个小东西功能如下:

    1. 选中select下拉菜单,点击添加就可以以标签的形式显示出来,见绿色区域。
    2. 点击绿色标签的关闭按钮可以删除该标签。
    3. 后续准备实现功能:封装成服务器端控件,方便在项目中使用。

    这其中的如下操作涉及到浏览器兼容:

    1. 动态添加的标签的css
    2. 添加标签的关闭点击事件

    常见的动态添加css可以使用object.setAttribute(sAttrName, vValue [, iCaseSensitive])方法。用法见MSDN 。

    这篇文章所诉:在目前为止的版本的IE浏览器当动态添加css的class时需要使用setAttribute("className",'classname'):国内网站上也是普遍的这种调调,但是注意:这篇文章发表于MAY 4, 2005。 当时还没有IE8,IE7。IE7中延续以前的做法,使用setAttribute("className","classname");的方法。

    如 

    1 obj.setAttribute("className","btn_close");

    但是在IE8中不同了,必须使用etAttribute("class","classname"),这也与chrome,firefox等浏览器兼容。

    MSDN原文
     The sAttrName parameter requires the name of the desired content attribute and not the Document Object Model (DOM) attribute. For example, in IE8 mode, this method no longer requires sAttrName to be "className" when setting, getting, or removing a CLASS attribute. Earlier versions of Internet Explorer and Internet Explorer 8 in compatibility mode still requiresAttrName to specify the corresponding DOM property name.

    综上,解决方案如下

    obj.setAttribute("className","classname");与obj.setAttribute("class","classname")成对出现即可,虽然有点丑陋,但是可以解决问题。

    完整解决方案

    var ieVersion = GetIeVersion();
            function GetIeVersion() {
                var reg = new RegExp("MSIE ([^;]*);", "i");
                if (reg.test(navigator.appVersion)) return parseInt(RegExp.$1);
                return 0;
            }
    	if(ieVersion>0&&ieVersion<8)
    		 obj.setAttribute("className","btn_close");
    	else
    		 obj.setAttribute("class","btn_close");
    

     再谈添加事件:

    可以使用如下代码

    1 var ele = document.createElement("a");
    2 ele.alt=VALUE;//要传递的参数 可以自定义一个属性(如if(!ele.attr){ele.attr=VALUE}),我习惯用alt
    3  if(window.addEventListener){ //FF
    4   ele.addEventListener("click",show,false);
    5 }else{ //IE chrome
    6 ele.attachEvent("onclick",show);
    7 }
    8
    9 function show() {
    10 //sreElement(IE)\target(FF) 获取事件源对象
    11 var srcEle=arguments[0].srcElement?arguments[0].srcElement:arguments[0].target;
    12 alert(srcEle.alt); //获取传递的参数值
    13 }

    代码复制自http://danjp.javaeye.com/blog/467007,详细请参看原文

  • 相关阅读:
    .net core 3.1 添加mysql ef core
    使用HttpContext.SignInAsync实现简单的授权
    linux部署harbor和基本使用
    委托,事件,Action , Func
    .net core 第三方Microsoft账号登录
    Persist Security Info 参数的作用
    SQL Server2008附加数据库之后显示为只读时解决方法
    Oracle 数据库学习笔记(五)(数据库修改密码(表密码,sys密码,system密码))
    JS做”返回顶部”按钮功能并实现滑动效果
    SQL Server 2008 允许远程链接 解决方法
  • 原文地址:https://www.cnblogs.com/x2048/p/1998161.html
Copyright © 2020-2023  润新知