DIV CSS 佈局教程網

jQuery 實作點擊輸入框彈出熱門標籤提示的完整範例
編輯:JQuery特效代碼     

部落格後台、發文頁面的標籤欄位,常用「點一下就把熱門標籤攤開來給你挑」的互動降低輸入成本。這個效果可以拆成三件事:定位彈出層、點擊外部關閉、點標籤自動填入並去重。以下是一份可直接運行的完整範例。

樣式與結構

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>jQuery 點擊文字框彈出熱門標籤提示示例</title>
<style type="text/css">
body { font-size:12px; font-family:Arial; }
#m_tagsItem {
    background:#fff; position:absolute; top:0px; left:0px; overflow:hidden;
    width:590px; *width:561px; width:561px\9;
    padding:10px; border:1px solid #ccc; z-index:1000; display:none;
}
#m_tagsItem p { text-align:left; line-height:22px; padding:2px 0; margin:0; border:0; }
#m_tagsItem span { font-weight:bold; }
#m_tagsItem a { margin:0 5px; }
.m_tagsname { color:#999; vertical-align:middle; font-size:12px; text-indent:3px; line-height:20px; }
#tagClose { font-size:12px; color:#888; cursor:pointer; position:absolute; top:2px; right:2px; }
</style>
<script src="https://www.webdm.cn/themes/script/jquery.js"></script>

IE6 的 z-index 補丁

舊版 IE 對 select 元素的層級處理有 bug,彈出層會被下拉選單穿透。經典解法是插入一個同樣絕對定位的透明 iframe 墊在下方:

<script language="javascript">
(function ($) {
$.fn.bgIframe = $.fn.bgiframe = function (s) {
    if ($.browser.msie && /6.0/.test(navigator.userAgent)) {
        s = $.extend({
            top: 'auto', left: 'auto', width: 'auto', height: 'auto',
            opacity: true, src: 'javascript:false;'
        }, s || {});
        var prop = function (n) { return n && n.constructor == Number ? n + 'px' : n; },
        html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="' + s.src + '"' +
            'style="display:block;position:absolute;z-index:-1;' +
            (s.opacity !== false ? 'filter:Alpha(Opacity=\'0\');' : '') +
            'top:' + (s.top == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')' : prop(s.top)) + ';' +
            'left:' + (s.left == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')' : prop(s.left)) + ';' +
            'width:' + (s.width == 'auto' ? 'expression(this.parentNode.offsetWidth+\'px\')' : prop(s.width)) + ';' +
            'height:' + (s.height == 'auto' ? 'expression(this.parentNode.offsetHeight+\'px\')' : prop(s.height)) + ';' +
            '"/>';
        return this.each(function () {
            if ($('> iframe.bgiframe', this).length == 0)
                this.insertBefore(document.createElement(html), this.firstChild);
        });
    }
    return this;
};
})(jQuery);

定位、開關與事件

jQuery.fn.selectCity = function (targetId) {
    var _seft = this;
    var targetId = $(targetId);
    this.click(function () {
        var A_top  = $(this).offset().top + $(this).outerHeight(true); // 貼齊輸入框下緣
        var A_left = $(this).offset().left;
        targetId.bgiframe();
        targetId.show().css({ "position": "absolute", "top": A_top + "px", "left": A_left + "px" });
    });
    targetId.find("#tagClose").click(function () { targetId.hide(); });
    $(document).click(function (event) {
        if (event.target.id != _seft.selector.substring(1)) { targetId.hide(); }
    });
    targetId.click(function (e) { e.stopPropagation(); }); // 避免點面板時被判定為點外部
    return this;
};
$(function () {
    $("#selecttags").selectCity("#m_tagsItem");
});

這裡有兩個關鍵技巧:一是用 offset() 加上 outerHeight(true) 算出輸入框下方的座標,讓面板永遠貼齊;二是 stopPropagation() 阻斷事件冒泡,否則點面板內部的標籤時,文件上的點擊監聽會誤判為「點了外面」而立即關閉。

點標籤自動填入並去重

function checktag(o) {
    var tagid = function (id) { return document.getElementById(id); }
    var tags = [];              // 存放既有標籤,避免重複加入
    var tagidSPLITCHAR = ' ';   // 分隔符,可依需求改為逗號或分號
    var d = tagid('selecttags');
    if (d.value) tags = d.value.split(tagidSPLITCHAR);
    var v = o.innerHTML;
    var s = tagidSPLITCHAR + tags.join(tagidSPLITCHAR) + tagidSPLITCHAR;
    if (!new RegExp(tagidSPLITCHAR + v + tagidSPLITCHAR, 'g').test(s)) {
        s += v;
    }
    s = s.replace(new RegExp("(^" + tagidSPLITCHAR + "*|" + tagidSPLITCHAR + "*tagid)", "g"), '');
    d.value = s;
    tags = s.split(tagidSPLITCHAR);
}

去重的做法是前後各補一個分隔符再組成正規表達式比對,這樣可以避免「美」誤配到「美妝」。若使用者可能輸入空白以外的分隔符,記得同步調整 tagidSPLITCHAR 與提示文案。

畫面部分

<body>
<input type="text" id="selecttags" name="m_tagsname" class="m_tagsname" style="width: 577px"
value="點擊查看熱門標籤和您曾經使用過的標籤"
onclick="if(this.value=='點擊查看熱門標籤和您曾經使用過的標籤'){this.value='';this.className='m_tagsname'}">
<div id="m_tagsItem" style="display: none">
    <div id="tagClose">關閉</div>
    <p><span>溫馨提示:</span>標籤間請用「空格」、「逗號」或「分號」隔開,用簡練的詞語概括您的博文內容。</p>
    <p><span>熱門標籤:</span><a href="javascript:void(0)" onclick="checktag(this)">彩妝</a><a href="javascript:void(0)" onclick="checktag(this)">美發</a><a href="javascript:void(0)" onclick="checktag(this)">美優博客</a><a href="javascript:void(0)" onclick="checktag(this)">天堂</a></p>
    <p><span>您使用過的標籤:</span><a href="javascript:void(0)" onclick="checktag(this)">軟件</a><a href="javascript:void(0)" onclick="checktag(this)">Delphi</a><a href="javascript:void(0)" onclick="checktag(this)">博客</a><a href="javascript:void(0)" onclick="checktag(this)">源碼</a></p>
</div>
</body>
</html>

整體拆開來看並不難:定位靠 offset(),開關靠 show/hide,關閉靠事件冒泡判斷,去重靠字串比對。若要在正式專案中使用,建議把 $.browser 相關判斷(jQuery 1.9 之後已移除)換成功能偵測,並把 javascript:void(0) 的寫法改為 button 元素,會更貼近現代開發慣例。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved