web前端開發小技巧(html+js)

來源:互聯網
上載者:User

1.frameset

 

一個html頁面內嵌入多個html頁,嵌入源碼如下:

Main.html

<frameset rows="100%,0,0,0,0" border="0"><frame src="roster.html" name="jwc_main" marginwidth="0"marginheight="0" scrolling="no"><frame src="empty.html" name="jwc_sound" marginwidth="0"marginheight="0" onLoad="soundLoaded();"></frameset>

在Main.js中,如果想設定frame中的值,可以進行如下操作:

 frames["jwc_main"].document.getElementById('myNickname').innerHTML = nick; 

指明frame的name,後面的操作就如同在roster.js一樣。

 

2.innerHTML

很多時候,頁面的參數是應該在js中動態設定的,那麼在相關html頁面中,就不需要制定文本具體內容了,相關源碼如下:

<span id="myNickname" class="nickName" title="Change User Info"></span> <span id="unit" class="unit"></span>

具體的值在相關js版面設定即可

 /* set nick */  document.getElementById('myNickname').innerHTML = "lethe";    /* set unit 2012.8.8 dml@wip Notice:This value should be catch from userInfo which is stored in openfire*/  document.getElementById('unit').innerHTML = "(ch)";  

3.div display

有的時候,一些標籤觸發才需要顯示,這個時候,寫個js方法就能解決了

<tr><td valign=top><img id="toggle_icon"src="images/group_close.gif" width="14" height="14"onClick="toggle_msgbox(this);"></td><td width="100%"><div id="face_tool" style="display:none"></div> <textarea id="msgbox" wrap="virtual"style="width:100%;height:1.4em;"onKeyPress="return msgboxKeyPressed(this,event);"onKeyDown="return msgboxKeyDown(this,event);"></textarea></td></tr>

預設的時候,face_tool不顯示,當點擊toggle_icon的時候,觸發toggle_msgbox(this)方法,顯示隱藏地區

function toggle_msgbox(el) {if (msgbox_toggled) {document.getElementById('msgbox').style.height = '1.4em';document.getElementById('chat').style.height = '100%';document.getElementById('submitbutton').style.display = 'none';document.getElementById('face_tool').style.display = 'none';el.src = group_close.src;} else {document.getElementById('msgbox').style.height = '4.2em';document.getElementById('chat').style.height = '99%';document.getElementById('submitbutton').style.display = '';document.getElementById('face_tool').style.display = '';el.src = group_open.src;}msgbox_toggled = !msgbox_toggled;}

4.top屬性

OO繼承思想來解決這個問題,看源碼:

Main.html

<frameset rows="100%,0,0,0,0" border="0"><frame src="roster.html" name="jwc_main" marginwidth="0"marginheight="0" scrolling="no"><frame src="empty.html" name="jwc_sound" marginwidth="0"marginheight="0" onLoad="soundLoaded();"></frameset>

roster.html

<span id="myNickname" class="nickName"onClick='return top.openUserInfo(top.cutResource(top.jid))'title="Change User Info"></span> 

這裡top.openUserInfo指的是main.js中的方法,也就是調用了祖先方法;相應的,有個parent屬性,是調用父親方法。

5.頁面許可權控制

有的時候,一些按鈕只針對特定的使用者,一些text只是本人可以編輯,js裡面,這個操作是很隨意的,看源碼:

vcard.html

<form>    <fieldset>      <legend>Name</legend>      <table>          <tr><th nowrap>Full Name:</th><td width="100%"><input type=text id="FN" class="vcardBoxEditable"></td></tr>          <tr><th nowrap>Family Name:</th><td width="100%"><input type=text id="N.FAMILY" class="vcardBoxEditable"></td></tr>          <tr><th nowrap>Given Name:</th><td width="100%"><input type=text id="N.GIVEN" class="vcardBoxEditable"></td></tr>      </table>    </fieldset>        <div id="savebox"><hr noshade size="1" size="100%"><div align="right"><button onClick="window.close();">Cancel</button> <button onClick="return sendSub();">Save</button></div>      </div>    </form>

vcard.js

for ( var i = 0; i < document.forms[0].elements.length; i++) {if (document.forms[0].elements[i].id == '')continue;if (cutResource(jid) != srcW.cutResource(srcW.jid)) {document.forms[0].elements[i].className = "vcardBox";document.forms[0].elements[i].readOnly = true;}}if (cutResource(jid) != srcW.cutResource(srcW.jid))document.getElementById("savebox").style.display = 'none';

vcard.css

.vcardBox {   border: 0;  background-color: #b8dbff;  width: 100%;}.vcardBoxEditable {   border: 1px;  background-color: white;  width: 100%;}

6.初始化select資訊

html中,select的option不固定,這個時候,javascript一些方法就顯示其功效了。

        <select size="1" name="groupName" id="groupName"><option value="all" selected>全部</option></select>

var obj = document.getElementById("groupName");obj.options.add(new Option("測試組1","g1"));//[顯示名],[值]

7.擷取同一頁面name相同,選中的tag值

<tr><td><input type="radio" value="images/image1.jpg"name="portrait" checked="checked"></td><td><img src="images/image1.jpg""></td><td><input type="radio" value="images/image2.jpg"name="portrait"></td><td><img src="images/image2.jpg""></td><td><input type="radio" value="images/image3.jpg"name="portrait"></td><td><img src="images/image3.jpg""></td></tr>

var New = document.getElementsByName("portrait");for ( var i = 0; i < New.length; i++) {if (New[i].checked) {portrait = New.item(i).getAttribute("value");}}

8.擷取url中的參數值

function GetRequest() {var url = location.search; // 擷取url中"?"符後的字串var theRequest = new Object();if (url.indexOf("?") != -1) {var str = url.substr(1);strs = str.split("&");for ( var i = 0; i < strs.length; i++) {theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);}}return theRequest;}

        var Request = new Object();Request = GetRequest();jid = Request['jid'];

或者

function getArgs() {passedArgs = new Array();search = self.location.href;search = search.split('?');if (search.length > 1) {argList = search[1];argList = argList.split('&');for ( var i = 0; i < argList.length; i++) {newArg = argList[i];newArg = argList[i].split('=');passedArgs[unescape(newArg[0])] = unescape(newArg[1]);}}}

getArgs();jid = passedArgs['jid'];

9.通過javascript配置css檔案資訊

style = "lethe.css"; // look for stylesheetif (parent.top.stylesheet)  style = parent.top.stylesheet;else if (top.opener.top.stylesheet)  style = top.opener.top.stylesheet;else if (top.opener.opener.top.stylesheet)style = top.opener.opener.top.stylesheet;document.write('<link rel="styleSheet" type="text/css" href="'+style+'">');

10.截取字串

function cutResource(aJID) { // removes resource from a given jidif (typeof (aJID) == 'undefined' || !aJID)return;var retval = aJID;if (retval.indexOf("/") != -1)retval = retval.substring(0, retval.indexOf("/"));return retval;}

11.標點符號encode

function msgEscape(msg) {if (typeof (msg) == 'undefined' || !msg || msg == '')return;msg = msg.replace(/%/g, "%25"); // must be done firstmsg = msg.replace(/\n/g, "%0A");msg = msg.replace(/\r/g, "%0D");msg = msg.replace(/ /g, "%20");msg = msg.replace(/\"/g, "%22");msg = msg.replace(/#/g, "%23");msg = msg.replace(/\$/g, "%24");msg = msg.replace(/&/g, "%26");msg = msg.replace(/\(/g, "%28");msg = msg.replace(/\)/g, "%29");msg = msg.replace(/\+/g, "%2B");msg = msg.replace(/,/g, "%2C");msg = msg.replace(/\//g, "%2F");msg = msg.replace(/\:/g, "%3A");msg = msg.replace(/\;/g, "%3B");msg = msg.replace(/</g, "%3C");msg = msg.replace(/=/g, "%3D");msg = msg.replace(/>/g, "%3E");msg = msg.replace(/@/g, "%40");return msg;}

12.htmlEnc

function htmlEnc(str) {if (!str)return '';str = str.replace(/&/g, "&");str = str.replace(/</g, "<");str = str.replace(/>/g, ">");str = str.replace(/\"/g, """);return str;}

13.判斷非法輸入

var prohibited = [ '"', ' ', '&', '\'', '/', ':', '<', '>', '@' ]; // invalid// charsfunction isValidJID(jid) {var nodeprep = jid.substring(0, jid.lastIndexOf('@')); // node name (string// before the @)for ( var i = 0; i < prohibited.length; i++) {if (nodeprep.indexOf(prohibited[i]) != -1) {alert("Invalid JID\n'" + prohibited[i]+ "' not allowed in JID.\nChoose another one!");return false;}}return true;}

14.擷取時間

function jabberDate(date) {if (!date.getUTCFullYear)return;var jDate = date.getUTCFullYear() + "-";jDate += (((date.getUTCMonth() + 1) < 10) ? "0" : "")+ (date.getUTCMonth() + 1) + "-";jDate += ((date.getUTCDate() < 10) ? "0" : "") + date.getUTCDate() + "T";jDate += ((date.getUTCHours() < 10) ? "0" : "") + date.getUTCHours() + ":";jDate += ((date.getUTCMinutes() < 10) ? "0" : "") + date.getUTCMinutes()+ ":";jDate += ((date.getUTCSeconds() < 10) ? "0" : "") + date.getUTCSeconds()+ "Z";return jDate;}

15.表情替換

function MsgReplace(msgHTML) {var regx = /(\[[\u4e00-\u9fa5]*\w*\]){1}/g;// 正則尋找“[]”格式var rs = msgHTML.match(regx);if (rs) {for (i = 0; i < rs.length; i++) { for (n = 0; n < em.length; n++) {if (em[n].phrase == rs[i]) {var t = "<img src='images/emotions/" + em[n].url + "' />";msgHTML = msgHTML.replace(rs[i], t);break;}}}}return msgHTML;}

16.解決IE不識別document.getElementsByName('xxxx')問題

<div name="histMsgInfo" id="histMsgInfo">xxxx</div>

所有同名name的id也需同名

var New = document.getElementsByName('histMsgInfo');for ( var i = 0; i < New.length; i++) {var histMsgInfo =New[i].innerHTML;histMsgInfo = MsgReplace(histMsgInfo);New[i].innerHTML=histMsgInfo;}

 17.設定檔以對象形式儲存和讀取

config.js

var BACKENDS = [ {name : "Open Relay",description : "HTTP Binding backend that allows connecting to any jabber server",httpbase : "/jointframe/JHB/",type : "binding",default_server : SITENAME} ];

xxxx.js

function init() {HTTPBASE = BACKENDS[0].httpbase;BACKEND_TYPE = BACKENDS[0].type;// bindingJABBERSERVER = BACKENDS[0].default_server;}

18.複選select

<td valign=top nowrap>選擇使用者(可複選):</td><td align=left width="100%"><select name="users_selector" id="users_selector" size=8 multiple style="width:100%;"></select></td>

var users_selector = document.getElementById('users_selector');for (var i=0; i < users_selector.options.length; i++) {if (users_selector.options[i].selected) {XXX.set('to',users_selector.options[i].value);}}

19.擷取iframe對象

function getPopupWinIframe(winId) {var stab = window.top.$('#' + winId, window.top.document.body);var siframe;if (stab && stab.find('iframe').length > 0) {siframe = stab.find('iframe')[0];}return siframe;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.