Re: src 与 srcset(或是 src-N)的 JS 交互

2013/10/25 Kang-Hao (Kenny) Lu <kanghaol@oupeng.com>

> (2013/10/25 21:52), John Hax wrote:
> > 1鐨勬柟娉曟槸鎶奿mg.src鏄庣‘涓烘渶缁堟樉绀虹殑鍥剧墖锛屼篃灏辨槸鎺掗櫎浜嗗悓鏃惰缃畇rcset/src
> > 鐨刢ase銆備篃灏辨槸璇村鏋滄墜鍔ㄨ缃簡src锛屽氨瑕嗙洊浜唖rcset鐨勮缃
>
> 濡傛灉鎴戞病寮勯敊浣犵殑鎰忔濄備綘鐨勬剰鎬濇槸鍦ㄨ繖涓柟娉曚腑
>
>   img.src = "picture-1.png";
>   img.srcset = "picture-2.png 2x";
>
> 鍦 window.devicePixelRatio = 2 鐨勬祻瑙堝櫒閲岋紝鍥犱负 .src 瑕嗙洊浜 .srcset 鐨勮
> 缃紝鎵浠ユ樉绀虹殑鍥剧墖鏄 "picture-1.png"锛
>


姝f槸濡傛銆備絾濡傛灉閬靛惊鎴戞墍璧炲悓鐨勬柟妗堬紝鍦ㄥ疄闄呭紑鍙戜腑鏄繖鏍峰啓鐨勶細

if ('srcset' in img) img.srcset = 'pic2.png 2x, pic1.png 1x'
else img.src = 'pic1.png'

鎵浠ヤ笉浼氬嚭鐜板湪鏀寔srcset鐨剅atio涓2鐨勬祻瑙堝櫒閲屾樉绀簆ic1鐨勯棶棰樸



> > 鏈鍚庯紝浣跨敤鏀寔srcset鐨勫簱銆傝剼鏈鏀瑰彉鍥剧墖锛屽彧鎿嶄綔srcset锛屼笉鎿嶄綔src銆
>
> 杩欓噷鏈変釜闂锛岀収 1) 璺熶綘璇 鈥滃彧鎿嶄綔srcset鈥 鐨勯昏緫锛屽鏋滀綘鐢ㄧ殑搴撶殑鎯呭舰鏄
>
>    HTML                       <img src=xxx srcset=xxx />
> +  涓嶆敮鎸 srcset 鐨 JS 搴 1   璁剧疆浜 .src
> +  鏀寔 srcset 鐨 JS 搴 2     璁剧疆浜 .srcset
>
> 閭h繖涓椂鍊 JS 搴 2 浼氫笉璧蜂綔鐢ㄣ傛敮鎸 .srcset 鐨 JS 搴撶殑瀹屾暣姝g‘鍐欐硶鏄
>

姝f槸濡傛銆傝繖閲岀殑鎯虫硶鏄紝铏界劧srcset涓嶈捣浣滅敤浜嗭紝浣嗘槸鑷冲皯鍔熻兘鏄彲鐢ㄧ殑锛屾棤闈炴槸閫鍖栧埌鍙湁src鐨勬儏鍐点備絾鍙嶈繃鏉ョ殑鎯呭喌灏辨湭蹇呰兘鎺ュ彈浜嗭紝鍥犱负瀹冨鑷村師鏈彲浠ョ敤鐨勫姛鑳藉け鏁堜簡锛堟敼鍙.src锛屽浘鐗囧嵈涓嶅彉锛夈


>
>   img.src = null;鈥
>   img.srcset = 鏂板;
>

> 锛岃涓嶅氨鏄祵涓嶄細杩炵画鐢ㄥ埌涓や釜鏀 .src/.srcset 鐨勫簱锛堝疄闄呬笂杩欑鎯呭喌鐨勭‘寰堝皯锛夈
>

涓嶆槸璧岋紝鑰屾槸瀹為檯寮鍙戜腑搴旇涓嶄細鍑虹幇杩欐牱鐨勬儏鍐碘斺斿鍚屼竴寮犲浘鐗囧悓鏃剁敤鏀.src鐨勮佺殑搴撳拰鏀.srcset鐨勬柊鐨勫簱銆

鎴戣涓哄疄闄呬笂瀹规槗鍑虹幇鐨勬儏褰㈡槸锛
1. 鍐呭杩涘寲鍒颁簡鐢@srcset锛屼絾搴撹繕鏄佺殑
2. 浠庤佺殑搴擄紙鐢╥mg.src锛夎浆鎹㈠埌鏂扮殑搴擄紙鐢╥mg.srcset锛


>
> > @src鏄粰涓嶆敮鎸乻rcset鐨刦allback銆
>
> 杩欐槸涓绉嶆兂娉曘備笉杩 Wikipedia 鐨勫仛娉曟槸鎶 1x 鐨 .png 鏀惧埌 @src 閲岋紝@srcset
> 娌℃湁 1x 鐨 .png锛
>

鐨勭‘鐜板湪鏄彲浠ヨ繖鏍风殑銆傝佸疄璇存垜璁や负杩欐槸涓笉濂界殑鍋氭硶銆傛垜鍏跺疄璁や负瑙勮寖搴旇鏀逛负鏈@srcset鏃跺彧鐢@srcset鑰屽拷鐣@src銆傝繖鏍峰叾瀹炵悊瑙h捣鏉ユ洿绠鍗曘

>
>   <img src="picture.png" srcset="picture-HD.png 2x" />
>
> 涓嶆槸 鈥滀笉鏀寔 @srcset 鐨 fallback鈥濄俧allback 鐨勬濈淮鐨勫啓娉曞簲璇ユ槸锛
>
>   <img src="picture.png" srcset="picture.png锛宲icture-HD.png 2x" />


> > 琛ㄩ潰涓婄湅锛岃繖涔熸湁鍚屾牱闂锛岃剼鏈鏋滆鏀瑰彉fallback鐨勫硷紝闇瑕
> > setAttribute('src', value)銆備絾鏄疄闄呬笂鏄笉闇瑕佽fallback鐨勶紝鑰屾槸鍐欐垚杩
> > 鏍 if ('srcset' in img) img.srcset = newSrcSet; else img.src =
> > newSrcFallback 灏卞彲浠ヤ簡銆傛敞鎰忚繖浠g爜鍗充娇瀵圭幇鍦ㄧ殑srcset瀹炵幇涔熸槸瀵圭殑銆
>
> 濡傛灉 newSrcSet 鏄 "picture-HD.png 2x" 鑰屼笉鏄 "picture.png锛宲icture-
> HD.png 2x"锛岄偅灏辨槸閿欑殑锛屽洜涓烘病鏈夎缃埌 1px 鐨勫浘鍍忋
>

纭疄銆備絾鏄湪瀹為檯褰撲腑锛岃繖涓嶆垚涓洪棶棰樸傚弽杩囨潵璇达紝鎴戞兂鍍忎笉鍒版湁鍙敼鍙2x 3x .5x鐨勫浘鐗囪屼笉鏀瑰彉1x鍥剧墖鐨勯渶姹傚晩銆


> > 杩欓噷鐨勮鐐规槸锛宧tml鍥犱负鏄潤鎬佺殑锛岄渶瑕佸悓鏃跺啓srcset鍜宻rc锛屼絾鏄剼鏈笉闇瑕
> > 鍚屾椂鍐欏叆銆
>
> 鏄備絾鏄瘮璧 1) 鎻愭瑕佹眰鐨
>
>   if ('srcset' in img)
>     img.srcset = newSrcSet;
>   else
>     img.src = newSrcFallback;
>
> 鍐欐硶锛2) 鎻愭瑕佹眰鐨
>
>   img.src = newSrcFallback;
>   img.srcset = newSrcSet;
>
> 灏戜簡涓よ锛岃櫧鐒堕『搴忚姹傜殑纭湁鐐瑰潙銆
>

浠g爜澶氬皯涓嶆槸闂銆傝兘鍚︾悊瑙f墠鏄棶棰樸@src鍜@srcset鏄苟瀛樺叧绯伙紝img.src鍜宨mg.srcset鍗存槸浜掔浉瑕嗙洊鐨勫叧绯伙紝鎬庝箞鐪嬮兘鏄竴浠跺鎬殑浜嬫儏銆


>
> > 娉ㄦ剰1鍜2鐨勫樊鍒槸锛氭柟妗1鐨刬mg.src姘歌繙override
> > @srcset鍜@src锛屾墍浠ヤ笉瀛樺湪浼樺厛绾ч棶棰橈紱鏂规2鐨剆rc鍜宻rcset灞炴ф槸鍜@src鍜
> > @srcset瀵瑰簲鐨勶紝灏变骇鐢熶簡浼樺厛绾с侀『搴忎箣绫荤殑闂銆
>
> 鍒繕浜嗘柟妗 1) 涔熻鐩 .srcset 浜嗐
>

浣嗘槸椤哄簭鏄崟涓鐨勶細

src > srcset > @srcset > @src

鑰屾柟妗2鐨勯『搴忓浣曠悊瑙e憿锛熷洶闅惧緱澶氬晩銆

Received on Sunday, 27 October 2013 12:57:59 UTC