JS代码实用代码实例(输入框监听,点击显示点击其他地方消失,文件本地预览上传)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS代码实用代码实例(输入框监听,点击显示点击其他地方消失,文件本地预览上传)相关的知识,希望对你有一定的参考价值。

前段时间写前端,遇到一些模块非常有用,总结以备后用

一.input框字数监听

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text"  name="wxChoiceInfo.infoTitle" id="wxChoiceInfoInfoTitle" size="120"  onkeyup="countNum(this)"/>
<div id="countNum" style="color: blue">还可输入<span id="num">140</span>个汉字</div>
<script src="static/js/jquery-1.12.4.js"></script>
<script>
    function countNum(e){
            var value=$(e).val();
            var cArr = value.match(/([\u0391-\uffe5])/ig); // 返回中文的字符
            var num=Math.floor((420-value.length-2*(cArr == null ? 0 : cArr.length))/3);
            $("#num").text(num);
            if(num>=0){
                $("#countNum").css({"color": "#FBBC05"});
            }else{
                $("#countNum").css({"color": "#EA4335"});
            }
        }
</script>

</body>
</html>

二.点输入框显示,点击页面其他地方隐藏功能

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#div1 {width:400px; height:300px; background:#CCC; display:none;}
</style>
<script>
window.onload=function ()
{
    var oBtn=document.getElementById(btn1);
    var oDiv=document.getElementById(div1);

    oBtn.onclick=function (ev)
    {
        var oEvent=ev||event;
        oDiv.style.display=block;
        //alert(‘按钮被点击了‘);

        oEvent.cancelBubble=true;
    };

    document.onclick=function ()
    {
        oDiv.style.display=none;
        //alert(‘document被点击了‘);
    };
};
</script>
</head>

<body>
<input id="btn1" type="button" value="显示" />
<div id="div1">
</div>
<div id="div2">

</div>
</body>
</html>

三.表情框

技术分享
// QQ表情插件
(function($){  
    $.fn.qqFace = function(options){
        var defaults = {
            id : ‘facebox‘,
            path : ‘face/‘,
            assign : ‘content‘,
            tip : ‘em_‘
        };
        var option = $.extend(defaults, options);
        var assign = $(‘#‘+option.assign);
        var id = option.id;
        var path = option.path;
        var tip = option.tip;
        
        if(assign.length<=0){
            alert(‘缺少表情赋值对象。‘);
            return false;
        }
        
        $(this).click(function(e){
            var strFace, labFace;
            if($(‘#‘+id).length<=0){
                strFace = ‘<div id="‘+id+‘" style="position:absolute;display:none;z-index:1000;" class="qqFace">‘ +
                              ‘<table border="0" cellspacing="0" cellpadding="0"><tr>‘;
                for(var i=1; i<=75; i++){
                    labFace = ‘[‘+tip+i+‘]‘;
                    strFace += ‘<td><img src="‘+path+i+‘.gif" onclick="$(\‘#‘+option.assign+‘\‘).setCaret();$(\‘#‘+option.assign+‘\‘).insertAtCaret(\‘‘ + labFace + ‘\‘);" /></td>‘;
                    if( i % 15 == 0 ) strFace += ‘</tr><tr>‘;
                }
                strFace += ‘</tr></table></div>‘;
            }
            $(this).parent().append(strFace);
            var offset = $(this).position();
            var top = offset.top + $(this).outerHeight();
            $(‘#‘+id).css(‘top‘,top);
            $(‘#‘+id).css(‘left‘,offset.left);
            $(‘#‘+id).show();
            e.stopPropagation();
        });

        $(document).click(function(){
            $(‘#‘+id).hide();
            $(‘#‘+id).remove();
        });
    };

})(jQuery);

jQuery.extend({ 
unselectContents: function(){ 
    if(window.getSelection) 
        window.getSelection().removeAllRanges(); 
    else if(document.selection) 
        document.selection.empty(); 
    } 
}); 
jQuery.fn.extend({ 
    selectContents: function(){ 
        $(this).each(function(i){ 
            var node = this; 
            var selection, range, doc, win; 
            if ((doc = node.ownerDocument) && (win = doc.defaultView) && typeof win.getSelection != ‘undefined‘ && typeof doc.createRange != ‘undefined‘ && (selection = window.getSelection()) && typeof selection.removeAllRanges != ‘undefined‘){ 
                range = doc.createRange(); 
                range.selectNode(node); 
                if(i == 0){ 
                    selection.removeAllRanges(); 
                } 
                selection.addRange(range); 
            } else if (document.body && typeof document.body.createTextRange != ‘undefined‘ && (range = document.body.createTextRange())){ 
                range.moveToElementText(node); 
                range.select(); 
            } 
        }); 
    }, 

    setCaret: function(){ 
        //if(!$.browser.msie) return;
        var initSetCaret = function(){
            var textObj = $(this).get(0);
            //textObj.caretPos = document.selection.createRange().duplicate();
        };
        $(this).click(initSetCaret).select(initSetCaret).keyup(initSetCaret); 
    }, 

    insertAtCaret: function(textFeildValue){ 
        var textObj = $(this).get(0); 
        if(document.all && textObj.createTextRange && textObj.caretPos){ 
            var caretPos=textObj.caretPos; 
            caretPos.text = caretPos.text.charAt(caretPos.text.length-1) == ‘‘ ? 
            textFeildValue+‘‘ : textFeildValue; 
        } else if(textObj.setSelectionRange){ 
            var rangeStart=textObj.selectionStart; 
            var rangeEnd=textObj.selectionEnd; 
            var tempStr1=textObj.value.substring(0,rangeStart); 
            var tempStr2=textObj.value.substring(rangeEnd); 
            textObj.value=tempStr1+textFeildValue+tempStr2; 
            textObj.focus(); 
            var len=textFeildValue.length; 
            textObj.setSelectionRange(rangeStart+len,rangeStart+len); 
            textObj.blur(); 
        }else{ 
            textObj.value+=textFeildValue; 
        } 
    } 
});
qqface.js
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>qqFace</title>
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" href="css/reset.css">    
<style>
.comment{width:680px; margin:20px auto; position:relative; background:#fff; padding:20px 50px 50px; border:1px solid #DDD; border-radius:5px;}
.comment h3{height:28px; line-height:28px}
.com_form{width:100%; position:relative}
.input{width:99%; height:60px; border:1px solid #ccc}
.com_form p{height:28px; line-height:28px; position:relative; margin-top:10px;}
span.emotion{width:42px; height:20px;}
span.emotion:hover{background-position:2px -28px}
.qqFace{margin-top:4px;background:#fff;padding:2px;border:1px #dfe6f6 solid;}
.qqFace table td{padding:0px;}
.qqFace table td img{cursor:pointer;border:1px #fff solid;}
.qqFace table td img:hover{border:1px #0066cc solid;}
#show{width:770px; margin:20px auto; background:#fff; padding:5px; border:1px solid #DDD; vertical-align:top;}

.sub_btn {
    position:absolute; right:0px; top:0;
    display: inline-block;
    zoom: 1; /* zoom and *display = ie7 hack for display:inline-block */
    *display: inline;
    vertical-align: baseline;
    margin: 0 2px;
    outline: none;
    cursor: pointer;
    text-align: center;
    font: 14px/100% Arial, Helvetica, sans-serif;
    padding: .5em 2em .55em;
    text-shadow: 0 1px 1px rgba(0,0,0,.6);
    -webkit-border-radius: 3px; 
    -moz-border-radius: 3px;
    border-radius: 3px;
    -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    -moz-box-shadow: 0 1px 2px rgba(0,0,0,.2);
    box-shadow: 0 1px 2px rgba(0,0,0,.2);
    color: #e8f0de;
    border: solid 1px #538312;
    background: #64991e;
    background: -webkit-gradient(linear, left top, left bottom, from(#7db72f), to(#4e7d0e));
    background: -moz-linear-gradient(top,  #7db72f,  #4e7d0e);
    filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr=‘#7db72f‘, endColorstr=‘#4e7d0e‘);
}
.sub_btn:hover {
    background: #538018;
    background: -webkit-gradient(linear, left top, left bottom, from(#6b9d28), to(#436b0c));
    background: -moz-linear-gradient(top,  #6b9d28,  #436b0c);
    filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr=‘#6b9d28‘, endColorstr=‘#436b0c‘);
}
</style>
</head>
<body>
     <div id="show"></div>
     <div class="comment">
        <div class="com_form">
            <textarea class="input" id="saytext" ></textarea>
            <p><input type="button" class="sub_btn" value="提交"><span class="emotion">表情</span></p>
        </div>
     </div>    

     
<script  src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.qqFace.js"></script>
<script type="text/javascript">
$(function(){
    $(‘.emotion‘).qqFace({
        id : ‘facebox‘, 
        assign:‘saytext‘, 
        path:‘arclist/‘    //表情存放的路径
    });
    $(".sub_btn").click(function(){
        var str = $("#saytext").val();
        $("#show").html(replace_em(str));
    });
});
//查看结果
function replace_em(str){
    str = str.replace(/\</g,‘&lt;‘);
    str = str.replace(/\>/g,‘&gt;‘);
    str = str.replace(/\n/g,‘<br/>‘);
    str = str.replace(/\[em_([0-9]*)\]/g,‘<img src="arclist/$1.gif" border="0" />‘);
    return str;
}
</script>

</body>
</html>

四. 文件本地预览上传

技术分享
function handleFileSelect(evt) {
    var files = evt.target.files;

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      // Only process image files.
      if (!f.type.match(‘image.*‘)) {
        continue;
      }

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
          var span = document.createElement(‘span‘);
          span.innerHTML = 
          [
            ‘<img style="height: 75px; border: 1px solid #000; margin: 5px" src="‘, 
            e.target.result,
            ‘" title="‘, escape(theFile.name), 
            ‘"/>‘
          ].join(‘‘);
          
          document.getElementById(‘list‘).insertBefore(span, null);
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

  document.getElementById(‘files‘).addEventListener(‘change‘, handleFileSelect, false);
fileLocalUpload.js
<input type="file" id="files" multiple />
<output id="list"></output>

 

以上是关于JS代码实用代码实例(输入框监听,点击显示点击其他地方消失,文件本地预览上传)的主要内容,如果未能解决你的问题,请参考以下文章

JS实现移动端实时监听输入框变化的实例代码

怎么监听一个input的value被js代码修改

js实现点击内容到文本框再点击更换内容

微信搜索栏输入代码

关于js中事件监听的问题(文本框 回车键 失去焦点)

JS或JQuery点击其他地方关闭弹出元素,但是点击元素却不会关闭的代码怎么写?