首页
留言
友情链接
Search
1
如何使用JavaScript获取和设置CSS root变量值
766 阅读
2
Centos7 下编译安装php8.2
275 阅读
3
春和 《江海共余生》
273 阅读
4
清除浮动,单行多行超出用...
273 阅读
5
hyperf常用命令
177 阅读
分享
Web前端
html&css
javascript
Vue
shopify
shoplazza
后端
ThinkPHP
YII2
服务器端
软件安装
故事
诗词
其他
抖音
快手
小视频
随笔
易经
书摘
问题合集
历史
登录
/
注册
Search
标签搜索
诗词
sunshine
累计撰写
105
篇文章
累计收到
7
条评论
首页
栏目
分享
Web前端
html&css
javascript
Vue
shopify
shoplazza
后端
ThinkPHP
YII2
服务器端
软件安装
故事
诗词
其他
抖音
快手
小视频
随笔
易经
书摘
问题合集
历史
页面
留言
友情链接
搜索到
22
篇与
的结果
2024-07-09
javascript 动态加载脚本
使用Promise 动态加载
2024年07月09日
8 阅读
0 评论
1 点赞
2024-07-03
防抖与节流
防抖与节流的区别:虽然防抖和节流都是优化高频率事件的方法,但它们有不同的侧重点:防抖(Debouncing):在特定时间内只执行一次函数,时间段内的重复调用会重新计时。适用于搜索输入、窗口调整大小等事件。节流(Throttling):限制函数在特定时间内执行的次数。适用于滚动事件、鼠标移动等。<script> function debounce(func, wait) { let timeout; return function (...args) { const context = this; clearTimeout(timeout); timeout = setTimeout(() => { func.apply(context, args); }, wait); }; } // 定义需要防抖的函数 function handleResize() { console.log('Window resized'); } // 创建防抖函数,设置等待时间为 300 毫秒 const debouncedResize = debounce(handleResize, 300); // 添加事件监听器 window.addEventListener('resize', debouncedResize); // 定义需要防抖的函数 function handleInput(event) { console.log('Input value:', event.target.value); } // 创建防抖函数,设置等待时间为 500 毫秒 const debouncedInput = debounce(handleInput, 500); // 添加事件监听器 // const inputElement = document.querySelector('input'); // inputElement.addEventListener('input', debouncedInput); // 节流函数实现 function throttle(func, wait) { let timeout; let lastRun = 0; return function (...args) { const context = this; const now = Date.now(); if (now - lastRun >= wait) { lastRun = now; func.apply(context, args); } else { clearTimeout(timeout); timeout = setTimeout(() => { lastRun = Date.now(); func.apply(context, args); }, wait - (now - lastRun)); } }; } // 节流函数使用示例 // 定义需要节流的函数 function handleScroll() { console.log('Scrolled'); } // 创建节流函数,设置等待时间为 200 毫秒 const throttledScroll = throttle(handleScroll, 200); // 添加事件监听器 window.addEventListener('scroll', throttledScroll); </script>
2024年07月03日
7 阅读
0 评论
0 点赞
2024-04-25
jquery 点击锚点事件并取消scroll事件,平滑滚动至锚点位置
在jQuery中,如果你想要取消由锚点点击触发的滚动事件,你可以使用event.preventDefault()方法来阻止默认的滚动行为。以下是一个简单的例子:$(document).ready(function(){ $('a[href*="#"]').click(function(event){ // 阻止默认的点击事件 event.preventDefault(); // 获取目标位置 var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); // 执行平滑滚动 if (target.length) { $('html, body').animate({ scrollTop: target.offset().top }, 1000); } }); });
2024年04月25日
70 阅读
0 评论
1 点赞
2023-08-28
javascript 邮箱校验
javascript 邮箱校验function isEmail(str) {var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;return reg.test(str);}
2023年08月28日
25 阅读
0 评论
0 点赞
2023-07-26
javascript 复制粘贴
<script> function sun_copy() { var coupon_code_dom = document.getElementById("coupon-code") var show_copy = document.getElementById("sunshine-copy") var coupon_code = coupon_code_dom.innerText var inp = document.createElement("input") document.body.appendChild(inp) inp.value = coupon_code inp.select() document.execCommand("copy", false) inp.remove() show_copy.innerText = 'Copied' } </script>
2023年07月26日
36 阅读
0 评论
0 点赞
2023-07-18
shopify 增加youtube视频和选项卡
引入相关资源<link rel="stylesheet" href="https://unpkg.com/element-ui@2.15.13/lib/theme-chalk/index.css"> <script src="https://cdn.shopify.com/s/files/1/0607/1861/2695/files/vue.min.js"></script> <script src="https://cdn.shopifycdn.net/s/files/1/0136/3119/3188/files/elementui-index.js"></script>sun-tab-video-css style liquid<style> * { margin: 0; padding: 0; box-sizing: border-box; } [v-cloak] { display: none; } @media (min-width: 1200px) { #shopify-section-header-08 .container, #shopify-section-navigation-08 .container { width: 1400px; } } .sun-video { width: 80%; margin: 50px auto; } .sun-video .video-group { display: flex; justify-content: space-between; margin: 10px 0; flex-wrap: wrap; } .sun-video .video-item { width: calc(100% / 3 - 10px); margin-top: 20px; } .sun-video .video-group:after { content: ""; display: block; width: calc(100% / 3 - 10px); height: 0; } .sun-video .video-title { display: -webkit-box; font-size: 20px; font-weight: bold; margin: 30px 0; text-align: center; min-height: 50px; overflow: hidden; text-overflow: ellipsis; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical; } .sun-video .video-content { width: 100%; text-align: center; } .sun-video .video-content:hover .play-button { background: #f00; } .sun-video .youtube { background-color: #000; margin-bottom: 30px; position: relative; padding-top: 56.25%; overflow: hidden; cursor: pointer; } .sun-video .youtube img { width: 100%; top: 0; left: 0; opacity: 0.8; } .sun-video .youtube img[data-class='default'] { top: -40px; } .sun-video .youtube .play-button { width: 90px; height: 60px; background-color: #000; box-shadow: 0 0 30px rgba(0, 0, 0, 0.6); z-index: 1; opacity: 0.8; border-radius: 6px; } .sun-video .youtube .play-button:before { display:block; content: ""; border-style: solid; border-width: 15px 0 15px 26.0px; border-color: transparent transparent transparent #fff; } .sun-video .youtube img, .sun-video .youtube .play-button { cursor: pointer; } .sun-video .youtube img, .sun-video .youtube iframe, .sun-video .youtube .play-button, .sun-video .youtube .play-button:before { position: absolute; } .sun-video .youtube .play-button, .sun-video .youtube .play-button:before { top: 50%; left: 50%; transform: translate3d(-50%, -50%, 0); display:block; } .sun-video .youtube iframe { height: 100%; width: 100%; top: 0; left: 0; } .sun-video .main-container-img img { width: 100%; } @media (max-width: 1000px) { .sun-video { width: 95%; } .sun-video .video-item { width: 100%; margin: 10px auto; } } @media (min-width: 1600px) { } </style> <style> .el-tabs__nav { width: 100%; } .el-tabs__item { padding: 0; width: calc(100% / {{ section.settings.tab_count | default: 2 }}); text-align: center; /*border-left: 1px solid #ccc;*/ /*border-top: 1px solid #ccc;*/ /*border-right: 1px solid #ccc;*/ /*border-bottom: 0;*/ } .el-tabs__item.is-active { color: #e71c20; } .el-tabs__active-bar { background-color: #e71c20; /*bottom: auto;*/ } .el-tabs__item:hover { color: #e71c20; } .el-tabs--card > .el-tabs__header .el-tabs__item.is-active { border-top: 2px solid #e71c20; } </style> <div class="sun-video" id="sun-video-app" v-cloak> <el-tabs id="sun-video-tab-content" v-model="activeName" @tab-click="handleClick" type="card"> </el-tabs> </div>html section {% if customer.id or true %} {% if section.settings.render_first %} {% render 'sun-tab-video-css' %} {% endif %} {% if section.settings.tab_title == blank %} <style> .el-tabs--card>.el-tabs__header{display:none;} </style> {% endif %} <div id="{{ section.id }}" style="display:none;"> {% if section.settings.tab_title %} <el-tab-pane label="{{ section.settings.tab_title }}" name="{% if section.settings.render_first %}first{% else %} {{ section.id }}{% endif %}"> {% endif %} <div class="video-group"> {% for block in section.blocks %} <div class="video-item"> <p class="video-title">{{ block.settings.title }}</p> <div class="video-content"> <div class="youtube" data-embed="{{ block.settings.embed_id }}" data-max="{{ block.settings.max }}"> <div class="play-button"></div> </div> </div> </div> {% endfor %} </div> {% if section.settings.tab_title %} </el-tab-pane> {% endif %} </div> <script> window.sunshine.tab_html = $('#{{ section.id }}').html(); $("#sun-video-tab-content").append(window.sunshine.tab_html) </script> {% if section.settings.render_last %} {% render 'sun-tab-video-js' %} {% endif %} {% endif %} {% schema %} { "name": "Sun Tab Video", "settings": [ { "type":"checkbox", "label":"Render First", "id":"render_first", "default": false }, { "type":"checkbox", "label":"Render Last", "id":"render_last", "default": false }, { "type":"number", "label":"Tab Count", "id":"tab_count" }, { "type":"text", "label":"Tab Title", "id":"tab_title" } ], "blocks":[ { "type":"text", "name":"Tab Item", "settings": [ { "type":"text", "id":"title", "label":"Item Title" }, { "type":"text", "id":"embed_id", "label":"Youtube Embed Id" }, { "type":"checkbox", "id":"max", "label":"Thumb Image Max?", "default":true } ] } ], "presets":[ { "name":"Sun Tab Video" } ] } {% endschema %}sun-tab-video-js <script> new Vue({ el: "#sun-video-app", delimiters: ['${', '}'], data: function () { return { activeName: 'first' } }, methods: { handleChange(val) { // console.log(val); }, handleClick(tab, event) { // console.log(tab, event); }, btn_submit() { // console.log('submit') } }, created() { }, computed: {} }) </script> <script> var youtube = document.querySelectorAll(".youtube"); // loop for (var i = 0; i < youtube.length; i++) { var source = ''; var img_class = ''; // thumbnail image source. if (youtube[i].dataset.max == 'true') { source = "https://img.youtube.com/vi/" + youtube[i].dataset.embed + "/maxresdefault.jpg"; img_class = 'max'; } else { source = "https://img.youtube.com/vi/" + youtube[i].dataset.embed + "/0.jpg"; img_class = 'default'; } var image = new Image(); image.src = source; image.setAttribute('data-class', img_class); image.addEventListener("load", function () { youtube[i].appendChild(image); }(i)); youtube[i].addEventListener("click", function () { var iframe = document.createElement("iframe"); iframe.setAttribute("frameborder", "0"); iframe.setAttribute("allowfullscreen", ""); iframe.setAttribute("src", "https://www.youtube.com/embed/" + this.dataset.embed + "?rel=0&autoplay=1&showinfo=1"); this.innerHTML = ""; this.appendChild(iframe); }); } </script>
2023年07月18日
26 阅读
0 评论
1 点赞
2023-07-13
Javascript 判断是否移动端
function isMobile() { var ua = navigator.userAgent; var ipad = ua.match(/(iPad).*OS\s([\d_]+)/), isIphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/), isAndroid = ua.match(/(Android)\s+([\d.]+)/); return isIphone || isAndroid; }
2023年07月13日
42 阅读
0 评论
1 点赞
2023-07-11
Shopify delivery date
Shopify delivery date<div class="sun-delivery"></div> <script> $(function () { const minDays = parseInt({{ block.settings.min_date | default: 0}}); const maxDays = parseInt({{ block.settings.max_date | default: 0 }}); const customText = '{{block.settings.custom_content}}'; const minDate = new Date(Date.now() + (minDays * 86400000)); const maxDate = new Date(Date.now() + (maxDays * 86400000)); const formatDate = (minDate.getFullYear() == maxDate.getFullYear() && minDate.getFullYear() == new Date().getFullYear()) ? new Intl.DateTimeFormat('en', {month: 'short', day: '2-digit'}) : new Intl.DateTimeFormat('en', {month: 'short', day: '2-digit', year: 'numeric'}); const tipText = customText.replace(/\{min_date\}/g, '<b>' + formatDate.format(minDate) + '</b>') .replace(/\{max_date\}/g, '<b>' + formatDate.format(maxDate) + '</b>'); $('.sun-delivery').html(tipText) }) </script>
2023年07月11日
40 阅读
0 评论
0 点赞
2023-07-08
axios 请求
安装使用 npm:$ npm install axios使用 bower:$ bower install axios使用 cdn:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>案例执行 GET 请求// 为给定 ID 的 user 创建请求 axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 上面的请求也可以这样做 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });执行 POST 请求axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });执行多个并发请求function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // 两个请求现在都执行完成 }));axios API可以通过向 axios 传递相关配置来创建请求axios(config) // 发送 POST 请求 axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); // 获取远端图片 axios({ method:'get', url:'http://bit.ly/2mTM3nY', responseType:'stream' }) .then(function(response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); axios(url[, config]) // 发送 GET 请求(默认的方法) axios('/user/12345');请求方法的别名axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]])注意在使用别名方法时, url、method、data 这些属性都不必在配置中指定。请求配置这些是创建请求时可以用的配置选项。只有 url 是必需的。如果没有指定 method,请求将默认使用 get 方法。{ // `url` 是用于请求的服务器 URL url: '/user', // `method` 是创建请求时使用的方法 method: 'get', // default // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。 // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL baseURL: 'https://some-domain.com/api/', // `transformRequest` 允许在向服务器发送前,修改请求数据 // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法 // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream transformRequest: [function (data, headers) { // 对 data 进行任意转换处理 return data; }], // `transformResponse` 在传递给 then/catch 前,允许修改响应数据 transformResponse: [function (data) { // 对 data 进行任意转换处理 return data; }], // `headers` 是即将被发送的自定义请求头 headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` 是即将与请求一起发送的 URL 参数 // 必须是一个无格式对象(plain object)或 URLSearchParams 对象 params: { ID: 12345 }, // `paramsSerializer` 是一个负责 `params` 序列化的函数 // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer: function(params) { return Qs.stringify(params, {arrayFormat: 'brackets'}) }, // `data` 是作为请求主体被发送的数据 // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH' // 在没有设置 `transformRequest` 时,必须是以下类型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - 浏览器专属:FormData, File, Blob // - Node 专属: Stream data: { firstName: 'Fred' }, // `timeout` 指定请求超时的毫秒数(0 表示无超时时间) // 如果请求话费了超过 `timeout` 的时间,请求将被中断 timeout: 1000, // `withCredentials` 表示跨域请求时是否需要使用凭证 withCredentials: false, // default // `adapter` 允许自定义处理请求,以使测试更轻松 // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)). adapter: function (config) { /* ... */ }, // `auth` 表示应该使用 HTTP 基础验证,并提供凭据 // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头 auth: { username: 'janedoe', password: 's00pers3cret' }, // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // default // `responseEncoding` indicates encoding to use for decoding responses // Note: Ignored for `responseType` of 'stream' or client-side requests responseEncoding: 'utf8', // default // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value xsrfHeaderName: 'X-XSRF-TOKEN', // default // `onUploadProgress` 允许为上传处理进度事件 onUploadProgress: function (progressEvent) { // Do whatever you want with the native progress event }, // `onDownloadProgress` 允许为下载处理进度事件 onDownloadProgress: function (progressEvent) { // 对原生进度事件的处理 }, // `maxContentLength` 定义允许的响应内容的最大尺寸 maxContentLength: 2000, // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte validateStatus: function (status) { return status >= 200 && status < 300; // default }, // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目 // 如果设置为0,将不会 follow 任何重定向 maxRedirects: 5, // default // `socketPath` defines a UNIX Socket to be used in node.js. // e.g. '/var/run/docker.sock' to send requests to the docker daemon. // Only either `socketPath` or `proxy` can be specified. // If both are specified, `socketPath` is used. socketPath: null, // default // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项: // `keepAlive` 默认没有启用 httpAgent: new http.Agent({ keepAlive: true }), httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' 定义代理服务器的主机名称和端口 // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据 // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。 proxy: { host: '127.0.0.1', port: 9000, auth: { username: 'mikeymike', password: 'rapunz3l' } }, // `cancelToken` 指定用于取消请求的 cancel token // (查看后面的 Cancellation 这节了解更多) cancelToken: new CancelToken(function (cancel) { }) }响应结构某个请求的响应包含以下信息{ // `data` 由服务器提供的响应 data: {}, // `status` 来自服务器响应的 HTTP 状态码 status: 200, // `statusText` 来自服务器响应的 HTTP 状态信息 statusText: 'OK', // `headers` 服务器响应的头 headers: {}, // `config` 是为请求提供的配置信息 config: {}, // 'request' // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance the browser request: {} }使用 then 时,你将接收下面这样的响应 :axios.get('/user/12345') .then(function(response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); });在使用 catch 时,或传递 rejection callback 作为 then 的第二个参数时,响应可以通过 error 对象可被使用配置默认值你可以指定将被用在各个请求的配置默认值全局的 axios 默认值axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';自定义实例默认值// Set config defaults when creating the instance const instance = axios.create({ baseURL: 'https://api.example.com' }); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 配置的优先顺序配置会以一个优先顺序进行合并。这个顺序是:在 lib/defaults.js 找到的库的默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后者将优先于前者。这里是一个例子:// 使用由库提供的配置的默认值来创建实例// 此时超时配置的默认值是 0var instance = axios.create(); // 覆写库的超时默认值 // 现在,在超时前,所有请求都会等待 2.5 秒 instance.defaults.timeout = 2500; // 为已知需要花费很长时间的请求覆写超时设置 instance.get('/longRequest', { timeout: 5000 }); 拦截器 在请求或响应被 then 或 catch 处理前拦截它们。 // 添加请求拦截器 axios.interceptors.request.use(function (config) { // 在发送请求之前做些什么 return config; }, function (error) { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器 axios.interceptors.response.use(function (response) { // 对响应数据做点什么 return response; }, function (error) { // 对响应错误做点什么 return Promise.reject(error); }); 如果你想在稍后移除拦截器,可以这样: const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor); 可以为自定义 axios 实例添加拦截器 const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/}); 错误处理 axios.get('/user/12345') .catch(function (error) { if (error.response) { // The request was made and the server responded with a status code // that falls out of the range of 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else if (error.request) { // The request was made but no response was received // `error.request` is an instance of XMLHttpRequest in the browser and an instance of // http.ClientRequest in node.js console.log(error.request); } else { // Something happened in setting up the request that triggered an Error console.log('Error', error.message); } console.log(error.config); });可以使用 validateStatus 配置选项定义一个自定义 HTTP 状态码的错误范围。axios.get('/user/12345', { validateStatus: function (status) { return status < 500; // Reject only if the status code is greater than or equal to 500 } })
2023年07月08日
38 阅读
0 评论
1 点赞
2023-06-13
浏览器禁止鼠标右键菜单
<script> if (document.images) { window.oncontextmenu = function () { return false; } }
2023年06月13日
109 阅读
0 评论
0 点赞
1
2
3