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>
时间: 2024-08-02 15:09:38

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

代码添加一个按钮及监听方法

有时候无法从控件中拖拽一个按钮到storyboard,必须用编写代码方式添加按钮: 1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 // Do any additional setup after loading the view, typically from a nib. 5 //计算出展示表情区域的宽和 展示区距顶部的高度+10个偏移量 6 //添加按钮 9 //创建button 10 addBtn = [[UIButton alloc

Ext JS 5的声明式事件监听

原文:Declarative Listeners in Ext JS 5 在前文<在Ext JS 5使用ViewControllers>中,简单的介绍了Ext JS 5的一项重要改进--声明式事件监听.在本文,将深度探讨如何使用声明式事件监听啦简化应用程序的视图并减少自定义组件的样板代码. 注意:文章假设你使用的是Ext JS 5.0.1或更高版本. 什么是声明式事件监听? 所谓的"声明式事件监听",就是指定义在类主体中的监听或在实例的配置对象中使用了listeners配置

Linux hostname对Oracle实例以及监听的影响

在Linux平台中,对hostname的修改,是否对ORACLE数据库实例或监听进程有影响呢?如果有影响,又要如何解决问题呢?另外/etc/hosts下相关内容的修改,是否也会影响实例或监听呢?这里涉及的场景非常多,当然关系也非常复杂,我们下面通过几个例子来测试验证一下. 如下所示,服务器/etc/hosts 与/etc/sysconfig/network的原始配置信息如下 [[email protected] ~]# more /etc/hosts # Do not remove the fo

ios开发-UI基础-应用管理(单纯界面)改进5-使用代理实现监听下载按钮的点击(delegate)

[注意]转载时请注明出处博客园-吃唐僧肉的小悟空http://www.cnblogs.com/hukezhu/ 前几篇文章介绍了一个应用管理的小应用,从最开始的单纯实现功能,一步一步就行改进\封装,上篇文章是使用xib进行了优化,本篇文章使用代理实现监听下载按钮的点击. 在原来的基础上,使用代理的主要思路分析: 首先要新建一个协议 声明协议的要实现的方法(一般为optional) 声明一个遵守该协议的代理的属性 使用代理,通知其代理完成操作 在代理中的实现步骤: 遵守协议 设置代理(一般通过拖线

[html5+java]文件异步读取及上传核心代码

html5+java 文件异步读取及上传关键代码段 功能: 1.多文件文件拖拽上传,file input 多文件选择 2.html5 File Api 异步FormData,blob上传,图片显示 3.java端接受 核心代码: 1.拖拽代码段: 1 <div id="dropzone"> 2 <div>Drag & drop your file here...</div> 3 <div id='showFile'></di

【转】Android开发20——单个监听器监听多个按钮点击事件

原文网址:http://woshixy.blog.51cto.com/5637578/1093936 原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://woshixy.blog.51cto.com/5637578/1093936 一.单个按钮点击事件的监听 方法一 /** * 从网络上获取图片 * * @author 徐越 * */ public class MainActivity extends Activity { pri

js上传文件带参数,并且,返回给前台文件路径,解析上传的xml文件,存储到数据库中

ajaxfileupload.js jQuery.extend({ createUploadIframe: function(id, uri) { //create frame var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) { var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '&qu

js实现上传图片本地预览功能

js: /**     * 上传图片本地预览方法     * @param {Object} fileObj 上传文件file的id元素  fresh-fileToUpload      * @param {Object} previewObj 上传图片的预览id元素  fresh-send-preview-img     * @param {Object} localImg 预览图片的父层id元素  fresh-send-preview-imgvideo     */    fs.setIma

v-once指令、v-cloak指令、条件指令家族、原义指令、循环指令、todolist案例、实例成员-符号、实例成员-计算属性、实例成员-属性监听、监听的案例、局部组件、全局组件、组件交互(父传子、子传父)

v-once指令: v-once:单独使用,限制的标签内容一旦赋值,便不可被动更改(如果是输入框,可以主动修改) <div id="app"> <input type="text" v-model="msg"> <!-- 一旦赋值,只可主动更改 --> <input type="text" v-model="msg" v-once> <p>{{ m