我在下面有一个名为“embed”的字符串,我想用比例因子(这里是.8)修改width参数。
scale = .8;
var embed = '<iframe width="960" height="315" src="//www.youtube.com/embed/kk5xfJodtrk" frameborder="0" allowfullscreen></iframe>';
所以当我完成后,嵌入字符串应该是:
embed = '<iframe width="768" height="315" src="//www.youtube.com/embed/kk5xfJodtrk" frameborder="0" allowfullscreen></iframe>';
实际上,宽度= 768,没有引号,也适用于我。
我尝试了很多东西。最新的是
var scale = .8;
var embed = '<iframe width="960" height="315" src="//www.youtube.com/embed/kk5xfK0ovrk" frameborder="0" allowfullscreen></iframe>';
var new_embed = embed.replace(/width="(\d+)/,"width=" + scale*$1);
但是这抱怨说1美元没有定义。
感谢您的帮助。
答案 0 :(得分:3)
//bit long, but works, can be shortened , no time :P
var scale = 0.5;
var embed = '<iframe width="960" height="315" src="//www.youtube.com/embed/kk5xfK0ovrk" frameborder="0" allowfullscreen></iframe>';
var embed = embed.replace(/width="(\d+)/,function myFunction(x){return "width=\""+x.replace("width=\"","") *scale;} );
var embed = embed.replace(/height="(\d+)/,function myFunction(y){return "height=\""+y.replace("height=\"","") *scale;} );
document.write(embed);
答案 1 :(得分:0)
不要使用正则表达式:
// create temporary element and parse HTML inside
var d = document.createElement('div');
d.innerHTML = embed;
// adjust width
d.firstChild.width *= 0.8;
// write into the document (or use appendChild)
document.write(d.innerHTML);