Jquery打造的类似新浪微博@提醒功能

时间:2024-04-05 21:06:53

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Jquery打造的类似新浪微博@提醒功能_网页代码站(www.webdm.cn)</title>
<style>
* { margin:0; padding:0;}
textarea { margin:20px 0 0 20px;}
</style>
<script src="http://www.webdm.cn/themes/script/jquery.js"></script>
<script>
$(function() {

var calculator = {
        // key styles
        primaryStyles: ['fontFamily', 'fontSize', 'fontWeight', 'fontVariant', 'fontStyle',
            'paddingLeft', 'paddingTop', 'paddingBottom', 'paddingRight',
            'marginLeft', 'marginTop', 'marginBottom', 'marginRight',
            'borderLeftColor', 'borderTopColor', 'borderBottomColor', 'borderRightColor',  
            'borderLeftStyle', 'borderTopStyle', 'borderBottomStyle', 'borderRightStyle',
            'borderLeftWidth', 'borderTopWidth', 'borderBottomWidth', 'borderRightWidth',
            'line-height', 'outline'],

specificStyle: {
            'word-wrap': 'break-word',
            'overflow-x': 'hidden',
            'overflow-y': 'auto'
        },
        
        simulator : $('<div id="textarea_simulator"/>').css({
                position: 'absolute',
                top: 0,
                left: 0,
                visibility: 'hidden'
            }).appendTo(document.body),

toHtml : function(text) {
            return text.replace(/\n/g, '<br>')
                .split(' ').join('<span style="white-space:prev-wrap">&nbsp;</span>');
        },
        // calculate position
        getCaretPosition: function() {
            var cal = calculator, self = this, element = self[0], elementOffset = self.offset();

// IE has easy way to get caret offset position
            /*if ($.browser.msie) {
                // must get focus first
                element.focus();
                var range = document.selection.createRange();  
                $('#hskeywords').val(element.scrollTop);
                return {  
                    left: range.boundingLeft - elementOffset.left,
                    top: parseInt(range.boundingTop) - elementOffset.top + element.scrollTop
                        + document.documentElement.scrollTop + parseInt(self.getComputedStyle("fontSize"))
                };  
            }  
*/            cal.simulator.empty();
            // clone primary styles to imitate textarea
            $.each(cal.primaryStyles, function(index, styleName) {
                self.cloneStyle(cal.simulator, styleName);
            });

// caculate width and height
            cal.simulator.css($.extend({
                'width': self.width(),
                'height': self.height()
            }, cal.specificStyle));

var value = self.val(), cursorPosition = self.getCursorPosition();
            var beforeText = value.substring(0, cursorPosition);
                atpos=beforeText.lastIndexOf('@');
                if(atpos!=-1){
                beforeText=beforeText.substring(0,atpos)
                afterText = value.substring(atpos);
                }else{
                afterText = value.substring(cursorPosition);
                }
            var before = $('<span class="before"/>').html(cal.toHtml(beforeText)),
                focus = $('<span class="focus"/>'),
                after = $('<span class="after"/>').html(cal.toHtml(afterText));

cal.simulator.append(before).append(focus).append(after);
            var focusOffset = focus.offset(), simulatorOffset = cal.simulator.offset();
            // alert(focusOffset.left  + ',' +  simulatorOffset.left + ',' + element.scrollLeft);
            return {
                top: focusOffset.top - simulatorOffset.top - element.scrollTop
                    // calculate and add the font height except Firefox
                    + ($.browser.mozilla ? 0 : parseInt(self.getComputedStyle("fontSize"))),
                left: focus[0].offsetLeft// -  cal.simulator[0].offsetLeft - element.scrollLeft
            };
        }
    };

$.fn.extend({
        getComputedStyle: function(styleName) {
            if (this.length == 0) return;
            var thiz = this[0];
            var result = this.css(styleName);
            result = result || ($.browser.msie ?
                thiz.currentStyle[styleName]:
                document.defaultView.getComputedStyle(thiz, null)[styleName]);
            return result;            
        },
        // easy clone method
        cloneStyle: function(target, styleName) {
            var styleVal = this.getComputedStyle(styleName);
            if (!!styleVal) {
                $(target).css(styleName, styleVal);
            }
        },
        cloneAllStyle: function(target, style) {
            var thiz = this[0];
            for (var styleName in thiz.style) {
                var val = thiz.style[styleName];
                typeof val == 'string' || typeof val == 'number'
                    ? this.cloneStyle(target, styleName)
                    : NaN;
            }
        },
        getCursorPosition : function() {
            var thiz = this[0], result = 0;
            if ('selectionStart' in thiz) {
                result = thiz.selectionStart;
            } else if('selection' in document) {
                var range = document.selection.createRange();
                if (parseInt($.browser.version) > 6) {
                    thiz.focus();
                    var length = document.selection.createRange().text.length;
                    range.moveStart('character', - thiz.value.length);
                    result = range.text.length - length;
                } else {
                    var bodyRange = document.body.createTextRange();
                    bodyRange.moveToElementText(thiz);
                    for (; bodyRange.compareEndPoints("StartToStart", range) < 0; result++)
                        bodyRange.moveStart('character', 1);
                    for (var i = 0; i <= result; i ++){
                        if (thiz.value.charAt(i) == '\n')
                            result++;
                    }
                    var enterCount = thiz.value.split('\n').length - 1;
                    result -= enterCount;
                    return result;
                }
            }
            return result;
        },
        getCaretPosition: calculator.getCaretPosition
    });
});
</script>
<script type="text/javascript">
/**
* 获取光标所在的字符位置
* @param obj 要处理的控件, 支持文本域和输入框
* @author hotleave
*/
function getInputPosition(obj){
var result = 0;
if(obj.selectionStart){ //非IE浏览器
result = obj.selectionStart
}else{ //IE
var rng;
if(obj.tagName == "TEXTAREA"){ //如果是文本域
rng = event.srcElement.createTextRange();
rng.moveToPoint(event.x,event.y);
}else{ //输入框
rng = document.selection.createRange();
}
rng.moveStart("character",-event.srcElement.value.length);
result = rng.text.length;
}
return result;
}
/*控制元素可见性*/
function showHide(classorid,show){
if(show>0){
$(classorid).show();
}else{
$(classorid).hide();
}
}
/************/
function getValue(obj){
// var pos = getInputPosition(obj); 这个方法或者插件里的方法都OK
var pos = $(obj).getCursorPosition();
var preval=obj.value.substr(0,pos);
var atpos=preval.lastIndexOf('@');
if(atpos>=0){
var atval=preval.substring(atpos+1,pos);
mousepos = $('textarea').getCaretPosition();
}
if(atval&&atval.length<20){
if(atval.match(/[^\u4e00-\u9fa5\w@_-]/g)){//匹配@后面有哪些内容时不出现提示
$('.wb_fb_notice').hide();
}else{
if($('.wb_fb_notice').html()==null){
$('body').append("<div class='wb_fb_notice' onclick=\"showHide('.wb_fb_notice',0)\">轻敲空格完成输入</div>");
$('.wb_fb_notice').css({left:$('#textarea').offset().left+mousepos.left,top:$('#textarea').offset().top+mousepos.top,position:'absolute',border:'1px solid #ccc',padding:'5px',background:"#fff",zIndex:'22',fontSize:'12px'});
}else{
$('.wb_fb_notice').css({left:$('#textarea').offset().left+mousepos.left,top:$('#textarea').offset().top+mousepos.top,position:'absolute',border:'1px solid #ccc',padding:'5px',background:"#fff",zIndex:'22',fontSize:'12px'});
$('.wb_fb_notice').show();
}
}
}else{
$('.wb_fb_notice').hide();
}
}
</script>
</head>
<body>
<div>
<textarea rows="6" cols="60" onmouseup="getValue(this)" onkeyup="getValue(this)" onblur="showHide('.wb_fb_notice',0)" id="textarea" >
<br>
<p><a href="http://www.webdm.cn">网页代码站</a> - 最专业的网页代码下载网站 - 致力为中国站长提供有质量的网页代码!</p>