繁体   English   中英

背景图片不适用于encodeURIComponent

[英]background-image not working with encodeURIComponent

我期待这能工作

var url = 'http://path_to_some_image.jpg';
$('body').css('background-image', "url('" + encodeURIComponent(url) + "')");

但是我得到404 not found错误。 为什么浏览器无法处理CSS中的编码URL?

如果我使用原始网址,则可以使用,但是如果网址中包含引号和内容,该怎么办? 我必须使用正则表达式手动替换它们:/

你应该做encodeURI

var url = 'http://path_to_some_image.jpg';
$('body').css('background-image', "url('" + encodeURI(url) + "')");

区别是

encodeURI假定输入是一个完整的URI,其中可能包含一些需要编码的字符。

encodeURIComponent将对具有特殊含义的所有内容进行编码,因此您可以将其用于URI之类的组件,例如

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM