js效果 整理

整理中。。。

 
1、js获取页面及元素高度、宽度

其他参考文献:http://www.open-open.com/lib/view/open1420120422531.html

js:

网页可见区域宽: document.body.clientWidth;(不含滚动条)
网页可见区域高: document.body.clientHeight;(不含滚动条)
网页可见区域宽: document.body.offsetWidth;(包括边线的宽);
网页可见区域高: document.body.offsetHeight;(包括边线的宽);
网页正文全文宽: document.body.scrollWidth;
网页正文全文高: document.body.scrollHeight;
网页被卷去的高(ff):document.body.scrollTop;
网页被卷去的高(ie): document.documentElement.scrollTop;
网页被卷去的左: document.body.scrollLeft;
网页正文部分上: window.screenTop;
网页正文部分左: window.screenLeft;
某个元素的宽度: obj.offsetWidth;
某个元素的高度: obj.offsetHeight;
某个元素的上边界到body最顶部的距离: obj.offsetTop;(在元素的包含元素不含滚动条的情况下)
某个元素的左边界到body最左边的距离: obj.offsetLeft;(在元素的包含元素不含滚动条的情况下)
返回当前元素的上边界到它的包含元素的上边界的偏移量: obj.offsetTop;(在元素的包含元素含滚动条的情况下)
返回当前元素的左边界到它的包含元素的左边界的偏移量: obj.offsetLeft;(在元素的包含元素含滚动条的情况下)

屏幕分辨率的高: window.screen.height
屏幕分辨率的宽: window.screen.width
屏幕可用工作区高度: window.screen.availHeight
屏幕可用工作区宽度: window.screen.availWidth

HTML精确定位:scrollLeft,scrollWidth,clientWidth,offsetWidth
scrollHeight: 获取对象的滚动高度。
scrollLeft:设置或获取位于对象左边界和窗口中目前可见内容的最左端之间的距离
scrollTop:设置或获取位于对象最顶端和窗口中可见内容的最顶端之间的距离
scrollWidth:获取对象的滚动宽度
offsetHeight:获取对象相对于版面或由父坐标 offsetParent 属性指定的父坐标的高度
offsetLeft:获取对象相对于版面或由 offsetParent 属性指定的父坐标的计算左侧位置
offsetTop:获取对象相对于版面或由 offsetTop 属性指定的父坐标的计算顶端位置
event.clientX 相对文档的水平座标
event.clientY 相对文档的垂直座标
event.offsetX 相对容器的水平坐标
event.offsetY 相对容器的垂直坐标
document.documentElement.scrollTop 垂直方向滚动的值
event.clientX+document.documentElement.scrollTop 相对文档的水平座标+垂直方向滚动的量

jquery:

获取浏览器显示区域(可视区域)的高度 : $(window).height();
获取浏览器显示区域(可视区域)的宽度 : $(window).width();
获取页面的文档高度:$(document).height();
获取页面的文档宽度 :$(document).width();
浏览器当前窗口文档body的高度: $(document.body).height();
浏览器当前窗口文档body的宽度: $(document.body).width();
获取滚动条到顶部的垂直高度 (即网页被卷上去的高度) :$(document).scrollTop();
获取滚动条到左边的垂直宽度 :$(document).scrollLeft();
获取或设置元素的宽度:$(obj).width();
获取或设置元素的高度:$(obj).height();

获取或设置元素的宽度:$(obj).innerWidth(); (height + padding)
获取或设置元素的高度:$(obj).innerHeight(); (height + padding)

获取或设置元素的宽度:$(obj).outerWidth(); (height + padding + border)
获取或设置元素的高度:$(obj).outerHeight(); (height + padding + border)

获取或设置元素的宽度:$(obj).outerWidth(true); (height + padding + border + margin)
获取或设置元素的高度:$(obj).outerHeight(true); (height + padding + border + margin)
某个元素的上边界到body最顶部的距离:obj.offset().top;(在元素的包含元素不含滚动条的情况下)
某个元素的左边界到body最左边的距离:obj.offset().left;(在元素的包含元素不含滚动条的情况下)
返回当前元素的上边界到它的包含元素的上边界的偏移量:obj.offset().top(在元素的包含元素含滚动条的情况下)
返回当前元素的左边界到它的包含元素的左边界的偏移量:obj.offset().left(在元素的包含元素含滚动条的情况下)

 
2、选中改变样式,其他默认样式

<dl class="use_class">
<dd>个人</dd>
<dd>机构</dd>
</dl>

<script type="text/javascript" src="../js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// 用户类别选择,个人、机构
$(document).ready(function(){
$("dd").click(function(){
$(this).css("background","#46b0d5").siblings().css("background","#ccc");
});
</script>
3、JS判断浏览器是否支持某一个CSS3属性的方法

css3表现冲击最大的就是动画了,因此很有必要去事先判断浏览器是否支持,写CSS3动画库就只有部分浏览器支持

function supportCss3(style) {
            var prefix = ['webkit', 'Moz', 'ms', 'o'],
                    i,
                    humpString = [],
                    htmlStyle = document.documentElement.style,
                    _toHumb = function (string) {
                        return string.replace(/-(w)/g, function ($0, $1) {
                            return $1.toUpperCase();
                        });
                    };

            for (i in prefix)
                humpString.push(_toHumb(prefix[i] + '-' + style));

            humpString.push(_toHumb(style));

            for (i in humpString)
                if (humpString[i] in htmlStyle) return true;

            return false;
        }
alert(supportCss3('animation-play-state'));//使用方法
4、JS实现-DIV自动居中代码
window.onload = function(){
            function box(){
                //获取DIV为‘box’的盒子
                var oBox = document.getElementById('box');
                //获取元素自身的宽度
                var L1 = oBox.offsetWidth;
                //获取元素自身的高度
                var H1 = oBox.offsetHeight;
                //获取实际页面的left值。(页面宽度减去元素自身宽度/2)
                var Left = (document.documentElement.clientWidth-L1)/2;
                //获取实际页面的top值。(页面宽度减去元素自身高度/2)
                var top = (document.documentElement.clientHeight-H1)/2;
                oBox.style.left = Left+'px';
                oBox.style.top = top+'px';
            }
            box();
            //当浏览器页面发生改变时,DIV随着页面的改变居中。
            window.onresize = function(){
                box();
            }
        }
5、JS自动刷新页面

Javascript刷新页面的几种方法:

1 history.go(0) 
2 location.reload() 
3 location=location 
4 location.assign(location) 
5 document.execCommand('Refresh') 
6 window.navigate(location) 
7 location.replace(location) 
8 document.URL=location.href

例如:

function myrefresh()
                {
                    window.location.reload();
                }
        setTimeout('myrefresh()',1000); //指定1秒刷新一次
6、点击空白关闭弹窗的js写法推荐?
$(document).mouseup(function(e){
  var _con = $(' 目标区域 ');   // 设置目标区域
  if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1
    some code...   // 功能代码
  }
});
/* Mark 1 的原理:
判断点击事件发生在区域外的条件是:
1. 点击事件的对象不是目标区域本身
2. 事件对象同时也不是目标区域的子元素
*/
7、js写一个弹出窗
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js实现一个弹出框</title>
<style type="text/css">
/*预先写好弹出窗的样式*/
#menu{height: 900px;}
#close{ 
    width:30px; 
    height:30px; 
    cursor:pointer; 
    position:absolute; 
    right:5px; 
    top:5px; 
    text-indent:-999em;
    background-color:blue;
    }
#mask{ 
    background-color:pink;
    opacity:0.5;
    filter: alpha(opacity=50); 
    position:absolute; 
    left:0;
    top:0;
    z-index:1;
    }
#login{ 
    position:fixed;
    z-index:2;
    }
.loginCon{ 
    position:relative; 
    width:670px;
    height:380px;
    /*background:url(img/loginBg.png) #2A2C2E center center no-repeat;*/
    background-color: #ccc;
    }
</style>
<script>
function openNew(){
    //获取页面的高度和宽度
    var sWidth=document.body.scrollWidth;
    var sHeight=document.body.scrollHeight;
    
    //获取页面的可视区域高度和宽度
    var wHeight=document.documentElement.clientHeight;
    
    var oMask=document.createElement("div");
        oMask.id="mask";
        oMask.style.height=sHeight+"px";
        oMask.style.width=sWidth+"px";
        document.body.appendChild(oMask);
    var oLogin=document.createElement("div");
        oLogin.id="login";
        oLogin.innerHTML="<div class='loginCon'><div id='close'>关闭</div></div>";
        document.body.appendChild(oLogin);
    
    //获取登陆框的宽和高
    var dHeight=oLogin.offsetHeight;
    var dWidth=oLogin.offsetWidth;
        //设置登陆框的left和top
        oLogin.style.left=sWidth/2-dWidth/2+"px";
        oLogin.style.top=wHeight/2-dHeight/2+"px";
    //点击关闭按钮
    var oClose=document.getElementById("close");
    
        //点击登陆框以外的区域也可以关闭登陆框
        oClose.onclick=oMask.onclick=function(){
                    document.body.removeChild(oLogin);
                    document.body.removeChild(oMask);
                    };
                    };
                    
    window.onload=function(){
            var oBtn=document.getElementById("btnLogin");
                //点击登录按钮
                oBtn.onclick=function(){
                    openNew();
                    return false;
                    }
                
        }
</script>

</head>
<body>
<div id="menu">
    <div id="login-area">
      <button id="btnLogin">登录</button>
    </div>
</div>
</body>
</html>
 8、限制显示字数
  8.1非文本框字数显示限制
var cname = document.getElementsByClassName('text-slick');
    for (var i = 0; i < cname.length; i++) {      
        var nowLength = cname[i].innerHTML.length;
        if (nowLength > wordLength) {
            cname[i].innerHTML = cname[i].innerHTML.substr(0,wordLength) + '...';
       }  
     } 
  8.2文本框字数显示限制
HTML代码:
其中:class="ui-text" 、class="ui-input"、data-num="48"、class="ui-textTips",是必不可少的。
<div class="ui-text">
    
     <textarea name="text" id="text" cols="" rows="" placeholder="" maxlength="48" class="ui-input" data-num="48"></textarea>
    <div class="ui-textTips">还可以输入<em>48</em>个字</div>
</div>

JS代码:

 1 function tipsText(){
 2     $('.ui-text').each(function(){
 3         var _this = $(this);
 4         var elm = _this.find('.ui-input');
 5         var txtElm = _this.find('.ui-textTips');
 6         var maxNum = _this.find('.ui-input').attr('data-num') || 500;
 7         console.log($.support.leadingWhitespace);
 8         if(!$.support.leadingWhitespace){
 9             _this.find('textarea').on('propertychange',function(){
10                 changeNum(elm,txtElm,maxNum);
11             });
12             _this.find('input').on('propertychange',function(){
13                 changeNum(elm,txtElm,maxNum);
14             });
15         } else {
16             _this.on('input',function(){
17                 changeNum(elm,txtElm,maxNum);
18             });
19         }
20     });
21 }
22  
23 tipsText();
24  
25 //获取文字输出字数,可以遍历使用
26 //txtElm动态改变的dom,maxNum获取data-num值默认为120个字,ps数字为最大字数*2
27 function changeNum(elm,txtElm,maxNum) {
28     //汉字的个数
29     //var str = (elm.val().replace(/w/g, "")).length;
30     //非汉字的个数
31     //var abcnum = elm.val().length - str;
32     total = elm.val().length;
33     if(total <= maxNum ){
34         texts = maxNum - total;
35         txtElm.html('还可以输入<em>'+texts+'</em>个字');
36     }else{
37         texts = total - maxNum ;
38         txtElm.html('已超出<em class="error">'+texts+'</em>个字');
39     }
40     return ;
41 }
42

文本框字数显示限制 方法二

  1 <html lang='en'>
  2     <head>
  3         <meta charset='utf-8'/>
  4         <title>demo</title>
  5         <style type="text/css">
  6         .sr { width: 300px; height: 300px; padding: 10px; outline: none; border: 1px solid #D4D4D4; background-color: #F3F3F3; }
  7         </style>
  8         
  9     </head>
 10     <body>
 11  
 12      <!-- onkeyUp="textLimitCheck(this, 20);" -->
 13     <textarea name="sca" class="sr" cols=45 rows=10 id="praiseName"></textarea>
 14         <br>
 15          <font color=#666666>限 6 个字符  已输入 <font color="#CC0000"><span id="info_limit">0</span></font> 个字</font>
 16  
 17          <script>
 18          /* 拼音输入法的时候字还没打完就被限制了。
 19 function textLimitCheck(thisArea, maxLength){
 20             if (thisArea.value.length > maxLength){ 
 21              alert(maxLength + ' 个字限制. 
超出的将自动去除.');   
 22            thisArea.value = thisArea.value.substring(0, 20); 
 23              thisArea.focus();    }    /*回写span的值,当前填写文字的数量*/  
 24           /*messageCount.innerText = thisArea.value.length; 
 25          }*/
 26  
 27         //控制字数
 28         var lim = new limit();
 29         lim.txtNote = document.getElementById("praiseName");   
 30         lim.txtLimit = document.getElementById("info_limit");  
 31         lim.limitCount = 6;
 32         lim.init();
 33         function limit(){ 
 34             var txtNote;//文本框
 35             var txtLimit;//提示字数的input
 36             var limitCount;//限制的字数
 37             this.init = function(){  
 38                 txtNote = this.txtNote;   
 39                 txtLimit = this.txtLimit;   
 40                 limitCount = this.limitCount; 
 41                 txtNote.maxLength = limitCount;
 42                 txtNote.onkeydown = function(){txtLimit.innerText = txtNote.value.length;};
 43                 txtNote.onkeyup = function(){txtLimit.innerText = txtNote.value.length;};
 44             }
 45         }
 46 // 输入法输入的时候,显示超出设置字数时进行截屏或者其他操作,操作完后,不会自动截取文字   所以需要输入框失去焦点时再截取一次
 47 
 48 $('#praiseName').blur(function() {
 49     $this = $(this);
 50     var val = $this.val();
 51     var length = $this.val().length;
 52     var lengthNum = 30;//设置限制的字数
 53 
 54     //超过指定字数便截取
 55     if (length > lengthNum) {
 56         var text = $this.val().substring(0, lengthNum);
 57         $this.val(text);
 58         $('#info_limit').text(lengthNum);
 59     };
 60 });
 61 //也可以直接在dom上加onblur事件οnblur="onsubstring();
 62 //function onsubstring(){
 63 //    var txtNote = document.getElementById("praiseName");   
 64 //    var txtLimit = document.getElementById("info_limit");  
 65 //    var limitCount = 6;
 66 //    if (txtNote.value.length > limitCount) {
 67 //        var text = txtNote.value.substring(0, limitCount);
 68 //        txtNote.value = text;
 69 //        txtLimit.innerText = limitCount;
 70 //    };
 71 //};
 72 
 73 //由于需要验证去除空格,我用到了jquery的 $.trim() 方法,去除输入的文字前后空格,基本满足要求
 74 $('#praiseName').blur(function() {  
 75     $this = $(this);  
 76     var val = $.trim($this.val());  
 77     $this.val(val);//去除空格后,重新赋值
 78     var length = $this.val().length;  
 79     var lengthNum = 8;//设置限制的字数  
 80     //超过指定字数便截取  
 81     if (length > lengthNum) {
 82         var text = $this.val().substring(0, lengthNum);
 83         $this.val(text);
 84         $('#info_limit').text(lengthNum);
 85     }else{
 86         $('#info_limit').text(length);
 87     };
 88 });
 89 
 90 //若需要多次使用,可采用下列修改
 91 $("#XX").blur(function(){
 92     blurLength($(this), 20, $('#XX'));
 93 });
 94 $("#XX").blur(function(){
 95     blurLength($(this), 90, $('#XX'));
 96 });
 97  
 98 //验证输入框字符串
 99 function blurLength(t, n, l){
100     var val = $.trim($(t).val());
101     $(t).val(val);//去除空格后,重新赋值
102     var length = $(t).val().length;
103     var lengthNum = n;//设置限制的字数
104     //超过指定字数便截取
105     if (length > lengthNum) {
106         var text = $(t).val().substring(0, lengthNum);
107         $(t).val(text);
108         $(l).text(lengthNum);
109     }else{
110         $(l).text(length);
111     };
112 }
113 //其他要求   需要在输入时判断只能输入数字和小数点。并且小数点后只保留两位
114 var lims = new limit();  
115     lims.txtNote = document.getElementById("diningPrice");     
116     lims.txtLimit = document.getElementById("diningPriceNum");    
117     lims.limitCount = 5;  
118     lims.mark = 1;  
119     lims.init(); 
120     function limit(){   
121         var txtNote;//文本框  
122         var txtLimit;//提示字数的input  
123         var limitCount;//限制的字数  
124         var mark;//判断标识
125         this.init = function(){    
126             txtNote = this.txtNote;     
127             txtLimit = this.txtLimit;     
128             limitCount = this.limitCount;   
129             mark = this.mark;
130             txtNote.maxLength = limitCount;  
131             txtNote.onkeydown = function(){
132                 if (mark == 1) {
133                     clearNoNum(txtNote);
134                 }
135                 txtLimit.innerText = txtNote.value.length;
136             };  
137             txtNote.onkeyup = function(){
138                 if (mark == 1) {
139                     clearNoNum(txtNote);
140                 }
141                 txtLimit.innerText = txtNote.value.length;
142             };  
143         }  
144     }  
145  
146     //过滤除数字和点外的其他输入内容
147     function clearNoNum(obj){ 
148         obj.value = obj.value.replace(/[^d.]/g,"");  //清除“数字”和“.”以外的字符  
149         obj.value = obj.value.replace(/.{2,}/g,"."); //只保留第一个. 清除多余的  
150         obj.value = obj.value.replace(".","$#$").replace(/./g,"").replace("$#$","."); 
151         obj.value = obj.value.replace(/^(-)*(d+).(dd).*$/,'$1$2.$3');//只能输入两个小数  
152         if(obj.value.indexOf(".")< 0 && obj.value !=""){//以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额 
153             obj.value= parseFloat(obj.value); 
154         }
155     }
156 //其他要求   限制只能输入中文、英文和数字
157 function limit(){   
158     var txtNote;//文本框  
159     var txtLimit;//提示字数的input  
160     var limitCount;//限制的字数  
161     this.init = function(){    
162         txtNote = this.txtNote;     
163         txtLimit = this.txtLimit;     
164         limitCount = this.limitCount;   
165         txtNote.maxLength = limitCount;  
166         txtNote.onkeydown = function(){
167             txtNote.value = txtNote.value.replace(/[^u4E00-u9FA5A-Za-z0-9]/g,'');
168             txtLimit.innerText = txtNote.value.length; 
169         };  
170         txtNote.onkeyup = function(){
171             txtNote.value = txtNote.value.replace(/[^u4E00-u9FA5A-Za-z0-9]/g,'');
172             txtLimit.innerText = txtNote.value.length; 
173         };  
174     }  
175 }
176 
177 
178 
179 
180 
181         </script>
182     </body>
183 </html>
原文地址:https://www.cnblogs.com/suming1016/p/5368825.html