JS共通コード
26891 ワード
1. PC - js は、指定範囲の乱数(m-n間)の式 を返す. return false return false Iframeによるネストを防止する 2 2種類の画像lazyロード方式第1個By JS中級交流群成都-猟巫第2個By上海-zenki ある年ある月の1日は何曜日の です
2. Mobile - js js判断IOS,アンドロイド
3.微信weixin UserAgent判断微信クライアント JSインタフェースのセキュリティドメイン名は記入されず、onMenuShareAppMessageを共有すると直接デフォルト値が取られます. 現在のページを閉じる 支払インタフェースメソッド呼び出しはaddeventで を呼び出す必要がある.支払インタフェースメソッド呼び出しは でなければならない.滝流無限ロード例 iOS、Safariブラウザ、inputなどのフォームfocus後fixed要素のずれ問題 地理的位置 を得る. rem計算適合 別のremスキーム jsが存在する経路 を取得する.グローバル取得エラー
1.一般的な方法-js文字列長切り取り はすべて を置換する.スペースをクリア 左スペース/右スペース をクリアは、ある文字列の先頭 であるか否かを判断する.ある文字列で終わるかどうかを判断する .エスケープhtmlタグ 日付フォーマット変換 デジタルタイプ であるか否かを判定する.クッキー値 を設定する. cookie値 を取得スタイルファイルテーブル をロードするは、スクリプトコンテンツ を返す.
Math.random()*(n-m)+m
// event.preventDefault() .
// event.stopPropagation() .
// return false :
// event.preventDefault();
// event.stopPropagation();
// callback function return
if(top != self){
location.href = ”about:blank”;
}
// @description
// css lazy-load-wrap
// data-lazy-src
// lazy-load-wrap , ,
//
$.fn.compassLazyLoad=function(){
var _HEIGHT=window.innerHeight,
_lazyLoadWrap=$('.lazy-load-wrap');
var methods={
setOffsetTop:function(){
$.each(_lazyLoadWrap,function(i,n){
$(n).attr({
'top':n.offsetTop-_HEIGHT,
'status':'wait'
});
})
},
isShow:function(){
var _scrollTop=$(window).scrollTop;
// image , image
$.each(_lazyLoadWrap,function(){
var _that=$(this);
if (_that.attr('status')==='done') {
return;
};
if (_that.attr('top')<=_scrollTop) {
_that.find('img[data-lazy-src]').each(function(i,n){
n.src=$(n).data('lazy-src');
});
_that.attr('status','done');
};
})
},
scroll:function(){
$(window).on('scroll',function(){
methods.isShow();
});
},
init:function(){
methods.setOffsetTop();
methods.isShow();
methods.scroll();
}
};
methods.init();
}
//
var exist=(function($){
var timer=null,
temp=[].slice.call($('.container'));
ret={};
for(var i=0,len=temp.length-1;i<=len;i++){
ret[i]=temp[i];
}
var isExist=function(winTop,winEnd){
for(var i in ret){
console.log(ret);
var item=ret[i],
eleTop=item.offsetTop,
eleEnd=eleTop+item.offsetHeight;
if((eleTop>winTop&&eleTop<=winEnd)||(eleEnd>winTop&&eleEnd<=winEnd)){
$(item).css('background','none');
new Tab($(item).attr('id'),data).init;
delete ret[i];
}
}
}
return {
timer:timer;
isExist:isExist;
};
})($);
//
Zepto(function ($) {
var swiper = new Swiper('.swiper-container', {
pagination: '.swiper-pagination',
paginationClickable: true,
autoplay: 3000,
loop: true,
autoplayDisableOnInteraction: false
});
(function lazyLoad() {
var imgs = $(".lazyLoad");
var src = '';
$.each(imgs, function (index, item) {
src = $(item).attr('data-src');
$(item).attr('src', src);
});
})();
});
$(function () {
var lazyLoadTimerId = null;
///
$(window).bind("scroll", function () {
clearTimeout(lazyLoadTimerId);
lazyLoadTimerId = setTimeout(function () {
//
var isHttp = (location.protocol === "http:");
$("#ym_images img").each(function () {
var self = $(this);
if (self.filter(":above-the-fold").length > 0) {
var originUrl = self.attr("data-original");
self.attr("src", originUrl);
}
});
}, 500);
});
});
var weekday = [" ", " ", " ", " ", " ", " ", " "];
weekday[new Date(2015, 9, 1).getDay()]; //2015 10 1
2. Mobile - js
var u = navigator.userAgent, app = navigator.appVersion;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android uc
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios
alert(' Android:'+isAndroid);
alert(' iOS:'+isiOS);
3.微信weixin
// Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12F70 MicroMessenger/6.1.5 NetType/WIFI
function isWechat() {
var ua = navigator.userAgent.toLowerCase();
return /micromessenger/i.test(ua) || /windows phone/i.test(ua);
}
// onMenuShareAppMessage
WeixinJSBridge.call('closeWindow');
document.addEventListener('WeixinJSBridgeReady', function onBridgeReady(){
that.initOrder();
}, false);
WeixinJSBridge.invoke('getBrandWCPayRequest', d, function(res){
if(res.err_msg == "get_brand_wcpay_request:ok"){
// alert(" ");
// union.release(d.orderId);
resetUrl();
paySuccess('home', d.orderId);
} else {
cancelOrder(d.orderId);
// alert(res.err_msg);
}
loading.hide();
});
// be dependent on jquery & jquery.infinitescroll.min.js
// insert this '' to your page.html
(function($){
$(function(){
var $container = $('.list-wrap-gd');
function layOutCallBack() {
$container.imagesLoaded(function(){
$container.masonry({
itemSelector: '.item-bar',
gutter: 10
});
});
$container.imagesLoaded().progress( function() {
$container.masonry('layout');
});
}
layOutCallBack();
$container.infinitescroll({
navSelector : "#more",
nextSelector : "#more a",
itemSelector : ".item-bar",
pixelsFromNavToBottom: 300,
loading:{
img: "/images/masonry_loading.gif",
msgText: ' ',
finishedMsg: " ",
finished: function(){
$("#more").remove();
$("#infscr-loading").hide();
}
},
errorCallback:function(){
$(window).unbind('.infscr');
},
pathParse: function (path, nextPage) {
var query = "";
var keyword=$("#search_keyword").val();
var cat_id=$("#cat_id").val();
var brand_id=$("#brand_id").val();
var country_id = $("#country_id").val();
query = query + "&namekeyword="+keyword;
query = query +"&cat_id="+cat_id
query = query + "&brand_id=" + brand_id;
query = query + "&country_id=" + country_id;
path = [path,query];
return path;
}
},
function(newElements) {
var $newElems = $( newElements ).css({ opacity: 0 });
$newElems.imagesLoaded(function(){
$newElems.animate({ opacity: 1 });
$container.masonry( 'appended', $newElems, true );
layOutCallBack();
});
});
});
})(jQuery);
if( /iPhone|iPod|iPad/i.test(navigator.userAgent) ) {
$(document).on('focus', 'input, textarea', function()
{
$('header').css("position", 'absolute');
$('footer').css("position", 'absolute');
});
$(document).on('blur', 'input, textarea', function()
{
$('header').css("position", 'fixed');
$('footer').css("position", 'fixed');
});
}
function getLocation(callback){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
function(p){
callback(p.coords.latitude, p.coords.longitude);
},
function(e){
var msg = e.code + "
" + e.message;
}
);
}
}
(function(doc, win){
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function(){
var clientWidth = docEl.clientWidth;
if(!clientWidth) return;
docEl.style.fontSize = 20 * (clientWidth / 320) + 'px';
};
if(!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
var dpr, rem, scale;
var docEl = document.documentElement;
var fontEl = document.createElement('style');
var metaEl = document.querySelector('meta[name="viewport"]');
dpr = window.devicePixelRatio || 1;
rem = docEl.clientWidth * 2 / 10;
scale = 1 / dpr;
// viewport, ,
metaEl.setAttribute('content', 'width=' + dpr * docEl.clientWidth + ',initial-scale=' + scale + ',maximum-scale=' + scale + ', minimum-scale=' + scale + ',user-scalable=no');
// data-dpr , css hack
docEl.setAttribute('data-dpr', dpr);
//
docEl.firstElementChild.appendChild(fontEl);
fontEl.innerHTML = 'html{font-size:' + rem + 'px!important;}';
// js , dpr rem px
window.rem2px = function(v) {
v = parseFloat(v);
return v * rem;
};
window.px2rem = function(v) {
v = parseFloat(v);
return v / rem;
};
window.dpr = dpr;
window.rem = rem;
function getJsDir (src) {
var script = null;
if (src) {
script = [].filter.call(document.scripts, function (v) {
return v.src.indexOf(src) !== -1;
})[0];
} else {
script = document.scripts[document.scripts.length - 1];
}
return script ? script.src.substr(0, script.src.lastIndexOf('/')) : script;
}
window.onerror = function (errMsg, scriptURI, lineNumber, columnNumber, errorObj) {
setTimeout(function () {
var rst = {
" :": errMsg,
" :": scriptURI,
" :": lineNumber,
" :": columnNumber,
" :": errorObj
};
alert(JSON.stringify(rst, null, 10));
});
};
1.一般的な方法-js
function cutstr(str, len) {
var temp,
icount = 0,
patrn = /[^\x00-\xff]/,
strre = "";
for (var i = 0; i < str.length; i++) {
if (icount < len - 1) {
temp = str.substr(i, 1);
if (patrn.exec(temp) == null) {
icount = icount + 1
} else {
icount = icount + 2
}
strre += temp
} else {
break;
}
}
return strre + "..."
}
String.prototype.replaceAll = function(s1, s2) {
return this.replace(new RegExp(s1, "gm"), s2)
}
String.prototype.trim = function() {
var reExtraSpace = /^\s*(.*?)\s+$/;
return this.replace(reExtraSpace, "$1")
}
function ltrim(s){ return s.replace( /^(\s*| *)/, ""); }
function rtrim(s){ return s.replace( /(\s*| *)$/, ""); }
String.prototype.startWith = function (s) {
return this.indexOf(s) == 0
}
String.prototype.endWith = function (s) {
var d = this.length - s.length;
return (d >= 0 && this.lastIndexOf(s) == d)
}
function HtmlEncode(text) {
return text.replace(/&/g, '&').replace(/\"/g, '"').replace(//g, '>')
}
Date.prototype.Format = function(formatStr) {
var str = formatStr;
var Week = [' ', ' ', ' ', ' ', ' ', ' ', ' '];
str = str.replace(/yyyy|YYYY/, this.getFullYear());
str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
str = str.replace(/M/g, (this.getMonth() + 1));
str = str.replace(/w|W/g, Week[this.getDay()]);
str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
str = str.replace(/d|D/g, this.getDate());
str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
str = str.replace(/h|H/g, this.getHours());
str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
str = str.replace(/m/g, this.getMinutes());
str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
str = str.replace(/s|S/g, this.getSeconds());
return str
}
function isDigit(value) {
var patrn = /^[0-9]*$/;
if (patrn.exec(value) == null || value == "") {
return false
} else {
return true
}
}
function setCookie(name, value, Hours) {
var d = new Date();
var offset = 8;
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
var nd = utc + (3600000 * offset);
var exp = new Date(nd);
exp.setTime(exp.getTime() + Hours * 60 * 60 * 1000);
document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString() + ";domain=360doc.com;"
}
function getCookie(name) {
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if (arr != null) return unescape(arr[2]);
return null
}
function LoadStyle(url) {
try {
document.createStyleSheet(url)
} catch(e) {
var cssLink = document.createElement('link');
cssLink.rel = 'stylesheet';
cssLink.type = 'text/css';
cssLink.href = url;
var head = document.getElementsByTagName('head')[0];
head.appendChild(cssLink)
}
}
function evalscript(s) {
if(s.indexOf(']*?>([^\x00]*?)<\/script>/ig;
var arr = [];
while(arr = p.exec(s)) {
var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i;
var arr1 = [];
arr1 = p1.exec(arr[0]);
if(arr1) {
appendscript(arr1[1], '', arr1[2], arr1[3]);
} else {
p1 = /<script(.*?)>([^\x00]+?)<\/script>/i;
arr1 = p1.exec(arr[0]);
appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1);
}
}
return s;
}</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">function stripscript(s) {
return s.replace(/<script.*?>.*?<\/script>/ig, '');
}</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">function appendscript(src, text, reload, charset) {
var id = hash(src + text);
if(!reload && in_array(id, evalscripts)) return;
if(reload && $(id)) {
$(id).parentNode.removeChild($(id));
}
evalscripts.push(id);
var scriptNode = document.createElement("script");
scriptNode.type = "text/javascript";
scriptNode.id = id;
scriptNode.charset = charset ? charset : (BROWSER.firefox ? document.characterSet : document.charset);
try {
if(src) {
scriptNode.src = src;
scriptNode.onloadDone = false;
scriptNode.onload = function () {
scriptNode.onloadDone = true;
JSLOADED[src] = 1;
};
scriptNode.onreadystatechange = function () {
if((scriptNode.readyState == 'loaded' || scriptNode.readyState == 'complete') && !scriptNode.onloadDone) {
scriptNode.onloadDone = true;
JSLOADED[src] = 1;
}
};
} else if(text){
scriptNode.text = text;
}
document.getElementsByTagName('head')[0].appendChild(scriptNode);
} catch(e) {}
}</code></pre>
<ul>
<li><p> ID </p></li>
</ul>
<pre><code class="js">function $(id) {
return !id ? null : document.getElementById(id);
}</code></pre>
<ul>
<li><p> URL </p></li>
</ul>
<pre><code class="js">function getUrlState(URL){
var xmlhttp = new ActiveXObject("microsoft.xmlhttp");
xmlhttp.Open("GET",URL, false);
try{
xmlhttp.Send();
}catch(e){
}finally{
var result = xmlhttp.responseText;
if(result){
if(xmlhttp.Status==200){
return(true);
}else{
return(false);
}
}else{
return(false);
}
}
}</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">var currentPageUrl = "";
if (typeof this.href === "undefined") {
currentPageUrl = document.location.toString().toLowerCase();
}else {
currentPageUrl = this.href.toString().toLowerCase();
}</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">function getPageHeight(){
var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat"
? a
: g.documentElement;
return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight);
}</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">function getPageViewWidth(){
var d = document, a = d.compatMode == "BackCompat" ?
d.body: d.documentElement;
return a.clientWidth;
}</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">function getPageWidth(){
var g = document, a = g.body, f = g.documentElement, d = g.compatMode == "BackCompat"?
a: g.documentElement;
return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth);
}</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">function uniqueId(){
var a=Math.random,b=parseInt;
return Number(new Date()).toString()+b(10*a())+b(10*a())+b(10*a());
}</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">Date.prototype.format = function(format){
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
};
if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
(this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o){
if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] :("00"+ o[k]).substr((""+ o[k]).length));
}
return format;
}
//
//new Date().format("yyyy-MM-dd hh:mm:ss");</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">function backTop(btnId) {
var btn = document.getElementById(btnId);
var d = document.documentElement;
var b = document.body;
window.onscroll = set;
btn.style.display = "none";
btn.onclick = function() {
btn.style.display = "none";
window.onscroll = null;
this.timer = setInterval(function() {
d.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
b.scrollTop -= Math.ceil((d.scrollTop + b.scrollTop) * 0.1);
if ((d.scrollTop + b.scrollTop) == 0) clearInterval(btn.timer, window.onscroll = set);
}, 10);
};
function set() {
btn.style.display = (d.scrollTop + b.scrollTop > 100) ? 'block': "none"
}
};
backTop('goTop');</code></pre>
<ul>
<li><p> URL GET </p></li>
</ul>
<pre><code class="js">// : test.htm?t1=1&t2=2&t3=3, :GET["t1"], GET["t2"], GET["t3"]
function get_get(){
querystr = window.location.href.split("?")
if(querystr[1]){
GETs = querystr[1].split("&");
GET = [];
for(i=0;i<GETs.length;i++){
tmp_arr = GETs.split("=")
key=tmp_arr[0]
GET[key] = tmp_arr[1]
}
}
return querystr[1];
}</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">String.prototype.unique=function(){
var x=this.split(/[\r
]+/);
var y='';
for(var i=0;i<x.length;i++){
if(!new RegExp("^"+x.replace(/([^\w])/ig,"\\$1")+"$","igm").test(y)){
y+=x+"\r
"
}
}
return y
};</code></pre>
<ul>
<li><p> , </p></li>
</ul>
<pre><code class="js">function SetSort(){
var text=K1.value.split(/[\r
]/).sort().join("\r
");//
var test=K1.value.split(/[\r
]/).sort().reverse().join("\r
");//
K1.value=K1.value!=text?text:test;
}</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">function IsReverse(text){
return text.split('').reverse().join('');
}</code></pre>
<ul>
<li><p> </p></li>
</ul>
<pre><code class="js">//
function transform(tranvalue) {
try {
var i = 1;
var dw2 = new Array("", " ", " "); //
var dw1 = new Array(" ", " ", " "); //
var dw = new Array(" ", " ", " ", " ", " ", " ", " ", " ", " ", " "); //
//
//
var source = splits(tranvalue);
var num = source[0];
var dig = source[1];
//
var k1 = 0; //
var k2 = 0; //
var sum = 0;
var str = "";
var len = source[0].length; //
for (i = 1; i <= len; i++) {
var n = source[0].charAt(len - i); //
var bn = 0;
if (len - i - 1 >= 0) {
bn = source[0].charAt(len - i - 1); //
}
sum = sum + Number(n);
if (sum != 0) {
str = dw[Number(n)].concat(str); // , str
if (n == '0') sum = 0;
}
if (len - i - 1 >= 0) { //
if (k1 != 3) { //
if (bn != 0) {
str = dw1[k1].concat(str);
}
k1++;
} else { // ,
k1 = 0;
var temp = str.charAt(0);
if (temp == " " || temp == " ") //
str = str.substr(1, str.length - 1);
str = dw2[k2].concat(str);
sum = 0;
}
}
if (k1 == 3){ //
k2++;
}
}
//
var strdig = "";
if (dig != "") {
var n = dig.charAt(0);
if (n != 0) {
strdig += dw[Number(n)] + " "; //
}
var n = dig.charAt(1);
if (n != 0) {
strdig += dw[Number(n)] + " "; //
}
}
str += " " + strdig;
} catch(e) {
return "0 ";
}
return str;
}
//
function splits(tranvalue) {
var value = new Array('', '');
temp = tranvalue.split(".");
for (var i = 0; i < temp.length; i++) {
value = temp;
}
return value;
}</code></pre>
</div>
</div>
</div>
</div>
<!--PC WAP -->
<div id="SOHUCS" sid="1176898182098006016"></div>
<script type="text/javascript" src="/views/front/js/chanyan.js">