我正在尝试将CSS应用于通过PHP创建的DOMDocument。然而,即使我使用jQuery来应用样式,它也不起作用。我举了一个例子:
<div id="content">
<p class="intro">Below are some of the YouTube videos I've made.
<br />Feel free to take a look!</p>
<div id="video-content">
<?php include '../resources/php/functions.php';
$functions=new Functions;
$functions->getVideos();
?>
<script type="text/javascript">
$(window).load(function() {
$('iframe-video').css({
"margin-left": "auto"
});
$('iframe-video').css({
"margin-right": "auto"
});
$('iframe-video').css({
"margin-bottom": "35px"
});
});
</script>
</div>
$functions->getVideos();
成功返回视频,并显示视频。他们还上了iframe视频课。然而,上面的CSS实际上并不适用于它
如何更改PHP DOMDocument生成的元素的CSS?
PHP代码如下:
public function getVideos() {
$doc = new DOMDocument;
libxml_use_internal_errors(true);
$doc->loadHTMLFile('http://www.youtube.com/user/HathorArts/videos');
libxml_use_internal_errors(false);
$xpath = new DOMXPath($doc);
$nodes = $xpath -> query('//a[@class="ux-thumb-wrap yt-uix-sessionlink yt-uix-contextlink yt-fluid-thumb-link contains-addto "]');
// Get the URLS for the videos, and build the iFrames for them.
$output = new DOMDocument;
foreach($nodes as $i => $node) {
// Creates the video URL for the iFrame
$temp_url = $node->getAttribute('href');
$replace_url = str_replace("/watch?v=", "", $temp_url);
$video_url = ("//www.youtube.com/embed/" . $replace_url . "?rel=0");
// Builds the iFrme
$iframe = $output->createElement('iframe');
$iframe->setAttribute('class', 'iframe-video');
$iframe->setAttribute('width', '560');
$iframe->setAttribute('height', '315');
$iframe->setAttribute('src', $video_url);
$iframe->setAttribute('frameborder', "0");
// Outputs the iFrame
$output->appendChild($iframe);
}
// Sends the output to the index file
echo $output -> saveHTML();
}
如果您有一个CSS文件,只需添加.iframe-video
的属性。PHP与CSS无关,只与HTML输出有关。
您应该在页面加载后延迟JavaScript代码,如下所示:
window.onload = function () { ... }
更改脚本代码中的几行;那么它就会起作用:
<script type="text/javascript">
$(document).ready(function() {
$('.iframe-video').css({
"margin-left": "auto"
});
$('.iframe-video').css({
"margin-right": "auto"
});
$('.iframe-video').css({
"margin-bottom": "35px"
});
});
</script>
这肯定会奏效。