[英]How to store css code in a php variable to be used with Javascript
I'm developing a product and one of the options I will provide is the ability to copy and paste your own CSS gradient code from reliable sources such as ColorZilla . 我正在开发一个产品,我将提供的一个选项是能够从可靠的来源(如ColorZilla)复制和粘贴您自己的CSS渐变代码。
How can I save such code in a PHP object (for use as default settings) and output it within javascript/jquery code while retaining the programming sense of the code. 如何在PHP对象中保存这些代码(用作默认设置)并在javascript / jquery代码中输出,同时保留代码的编程意义。 I have tried using "addslashes()" to no avail. 我试过使用“addslashes()”无济于事。
At the moment, I've got: 目前,我有:
$default_options = array(
'header_wrap_grad' => '
background: rgb(169,3,41); /* Old browsers */
background: -moz-linear-gradient(top, rgba(169,3,41,1) 0%, rgba(143,2,34,1) 44%, rgba(109,0,25,1) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(169,3,41,1)), color-stop(44%,rgba(143,2,34,1)), color-stop(100%,rgba(109,0,25,1))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, rgba(169,3,41,1) 0%,rgba(143,2,34,1) 44%,rgba(109,0,25,1) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, rgba(169,3,41,1) 0%,rgba(143,2,34,1) 44%,rgba(109,0,25,1) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, rgba(169,3,41,1) 0%,rgba(143,2,34,1) 44%,rgba(109,0,25,1) 100%); /* IE10+ */
background: linear-gradient(top, rgba(169,3,41,1) 0%,rgba(143,2,34,1) 44%,rgba(109,0,25,1) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\'#a90329\', endColorstr=\'#6d0019\',GradientType=0 ); /* IE6-9 */
',
Then later on within the tags Ive got : 然后在我得到的标签内:
$('#header-wrap-grad').attr('value', '<?php echo addslashes($default_options['header_wrap_grad']); ?>');
with #header-wrap-grad being the textarea that I'm trying to populate with the css code from the variable. #header-wrap-grad是我试图用变量中的css代码填充的textarea。 However, this isn't working. 但是,这不起作用。 Im getting this error "Unexpected token :" when I try to echo out the variable. 当我尝试回显变量时,我收到此错误“意外的令牌:”。
Can someone point me in the right direction please? 有人能指出我正确的方向吗?
Thanks. 谢谢。
您正在创建JavaScript字符串,因此请使用json_encode(并且不包含引号):
$('#header-wrap-grad').attr('value', <?php echo json_encode($default_options['header_wrap_grad']); ?>);
You have problems with the line-breaks inside the string, they will break the JS-code. 你对字符串中的换行有问题,它们会破坏JS代码。
You may encode the string in PHP with rawurlencode and decode the string in JS with decodeURIComponent. 您可以使用rawurlencode在PHP中对字符串进行编码,并使用decodeURIComponent解码JS中的字符串。
$('#header-wrap-grad')
.attr('value',
decodeURIComponent('<?php echo rawurlencode($default_options['header_wrap_grad']); ?>'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.