使用现有代码根据浏览器宽度更改图像 url
Changing image url based on broswer width with existing code
我是 JavaScript 的新人,所以如果有人问这个问题,请原谅我。
我想让我的 img
标签响应,所以我使用这个:
<img data-nsrc="<?php
echo wp_get_attachment_image_src( get_post_thumbnail_id()
, 'small-post'
, false )[0] ?>"
data-msrc="<?php
echo wp_get_attachment_image_src( get_post_thumbnail_id()
, 'mobile-img', false )[0] ?>"
src="<?php echo wp_get_attachment_image_src( get_post_thumbnail_id()
, 'small-post'
, false )[0] ?>"
class="img-right resimgsm">
我更改了代码以使用 img
,就像之前我使用 div
和 inline CSS
以及 background image
。
这是页面底部的script
运行:
<script>
jQuery(document).ready(function(){
jQuery( window ).resize(function(ev) {
var w=jQuery( window ).width();
if(w>600){
jQuery.each(jQuery('.resimgsm'),function(i,el){
jQuery(el).attr('src',"background-image: url('"+jQuery(el).attr('data-nsrc')+"')")
})
}else{
jQuery.each(jQuery('.resimgsm'),function(i,el){
jQuery(el).attr('src',"background-image: url('"+jQuery(el).attr('data-msrc')+"')")
})
}
});
jQuery(window).trigger('resize')
})
</script>
有人可以告诉我如何改变这个吗?感谢您的帮助。
更改图像源与您之前的非常相似,您只需要直接图像URL:
if(w>600){
jQuery.each(jQuery('.resimgsm'),function(i,el){
jQuery(el).attr('src',jQuery(el).attr('data-nsrc'))
})
}else{
jQuery.each(jQuery('.resimgsm'),function(i,el){
jQuery(el).attr('src', jQuery(el).attr('data-msrc'))
})
}
简短说明
你以前的样子可能是这样的:
<div style="background-image: url(imageURLHere.jpg);"></div>
并且您正在修改样式属性或 CSS 属性。
你现在拥有的应该是这样的:
<img src="imageURLHere.jpg">
上面的代码就是这样做的。
我是 JavaScript 的新人,所以如果有人问这个问题,请原谅我。
我想让我的 img
标签响应,所以我使用这个:
<img data-nsrc="<?php
echo wp_get_attachment_image_src( get_post_thumbnail_id()
, 'small-post'
, false )[0] ?>"
data-msrc="<?php
echo wp_get_attachment_image_src( get_post_thumbnail_id()
, 'mobile-img', false )[0] ?>"
src="<?php echo wp_get_attachment_image_src( get_post_thumbnail_id()
, 'small-post'
, false )[0] ?>"
class="img-right resimgsm">
我更改了代码以使用 img
,就像之前我使用 div
和 inline CSS
以及 background image
。
这是页面底部的script
运行:
<script>
jQuery(document).ready(function(){
jQuery( window ).resize(function(ev) {
var w=jQuery( window ).width();
if(w>600){
jQuery.each(jQuery('.resimgsm'),function(i,el){
jQuery(el).attr('src',"background-image: url('"+jQuery(el).attr('data-nsrc')+"')")
})
}else{
jQuery.each(jQuery('.resimgsm'),function(i,el){
jQuery(el).attr('src',"background-image: url('"+jQuery(el).attr('data-msrc')+"')")
})
}
});
jQuery(window).trigger('resize')
})
</script>
有人可以告诉我如何改变这个吗?感谢您的帮助。
更改图像源与您之前的非常相似,您只需要直接图像URL:
if(w>600){
jQuery.each(jQuery('.resimgsm'),function(i,el){
jQuery(el).attr('src',jQuery(el).attr('data-nsrc'))
})
}else{
jQuery.each(jQuery('.resimgsm'),function(i,el){
jQuery(el).attr('src', jQuery(el).attr('data-msrc'))
})
}
简短说明
你以前的样子可能是这样的:
<div style="background-image: url(imageURLHere.jpg);"></div>
并且您正在修改样式属性或 CSS 属性。
你现在拥有的应该是这样的:
<img src="imageURLHere.jpg">
上面的代码就是这样做的。