看板 Web_Design 關於我們 聯絡資訊
大家好, 最近在寫一個 userscript,要把每一個 img 都加上一個 canvas。 剛開始是用 jQuery("img").each 先 wrap div 再加入 canvas。搞定 position, padding 後還有一個問題,就是有時圖片還沒載完, width, height 是 0,則會造成圖片跑掉。 jQuery("img").each((_, e) => { jQuery(e).wrap(`<div style="position: relative; display: block; margin: 0px auto; width: ${e.width}px!important; height: ${e.height}px!important;">`); jQuery(e).after(`<canvas style="position: absolute; top: 0px; left: 0px; width: ${e.width}px; height: ${e.height}px; padding-top: ${e.style.paddingTop};!important">`); jQuery(e).css("margin-left","0px"); jQuery(e).css("margin-right","0px"); }); Google 一下應該要用 load 事件: jQuery("img").load(() => { jQuery(this).wrap(`<div style="position: relative; display: block; margin: 0px auto; width: ${this.width}px!important; height: ${this.height}px!important;">`); jQuery(this).after(`<canvas style="position: absolute; top: 0px; left: 0px; width: ${this.width}px; height: ${this.height}px; padding-top: ${this.style.paddingTop};!important">`); jQuery(this).css("margin-left","0px"); jQuery(this).css("margin-right","0px"); }); 卻發現 jq 早就拿掉 load 惹,但就算改成: jQuery("img").on("load", () => { alert(""); jQuery(this).wrap(`<div style="position: relative; display: block; margin: 0px auto; width: ${this.width}px!important; height: ${this.height}px!important;">`); jQuery(this).after(`<canvas style="position: absolute; top: 0px; left: 0px; width: ${this.width}px; height: ${this.height}px; padding-top: ${this.style.paddingTop};!important">`); jQuery(this).css("margin-left","0px"); jQuery(this).css("margin-right","0px"); }); 非但沒做任何事,甚至連 alert 都沒出現!我記得我今天在亂試中有成功過 R!現在完全 沒有頭緒,請各位大大不吝給予意見指教! P.S. 如我這般欲將每一 img 加上 canvas,倘若遇到後來 ajax 才載入之圖片要怎麼辦? 再監聽一個 scroll 事件感覺很浪費資源 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 106.107.240.213 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Web_Design/M.1560788171.A.E4A.html
LoveMoon: 1.load() still works;2.change ()=>{} to function(){} 06/18 20:08
LoveMoon: be sure that the "this" keyword refers to right obj 06/18 20:09
LoveMoon: u should know all the cods u write 06/18 20:11
研究惹一番,終於 OK 喇 let mo = new MutationObserver(i => { $("img").each((_, e) => { if (e.width && e.height) $(e).wrap(`<div style="position: relative; display: block; margin: 0px auto;>`) .after(`<canvas style="position: absolute; top: 0px; left: 0px; width: ${e.width}px; height: ${e.height}px; padding-top: ${e.style.paddingTop};!important">`) .css("margin-left","0px") .css("margin-right","0px"); else e.onload += () => { $(this).wrap(`<div style="position: relative; display: block; margin: 0px auto;">`) .after(`<canvas style="position: absolute; top: 0px; left: 0px; width: ${this.width}px; height: ${this.height}px; padding-top: ${this.style.paddingTop};!important">`) .css("margin-left","0px") .css("margin-right","0px"); }; }); }); mo.observe(document, {subtree: true, childList: true}); ※ 編輯: nevikw39 (106.107.240.213 臺灣), 06/18/2019 22:35:28