我一直在寻找解决方案,并阅读了很多关于图像大小调整和DOM节点搜索以及Wordpress功能的文章以及任何其他可能的方法。
继承人的情景......
我正在为客户创建Wordpress的自定义主题。这是一个报纸网站,需要它按比例自动调整图片大小以适应页面上某个框的功能。通常我会在CSS中设置width:SomeWidth
,但我没有任何方法来识别img。
我的索引页面是一个框架,wordpress引擎加载内容。这意味着在向用户显示之前,我无法控制图像上的属性。 (是的,我们可以手动调整每张图片的大小,但我的客户不希望这样做,而且她也希望它是单页上的原始尺寸。
这是一个方框:
<div class="box-center">
<h1>Music 101</h1>
<div class="box-inner-center">
<ul>
<?php
global $post;
$args = array('numberposts'=>1,'category'=>get_cat_ID('Music 101'));
$myposts=get_posts($args);
foreach($myposts as $post) : setup_postdata($post); ?>
<li><?php the_content(); ?></li>
<?php endforeach; ?>
</ul>
<a class="more" href="<?php echo esc_url(get_category_link(get_cat_ID('Music 101'))); ?>">More Music 101 >></a>
</div>
</div>
页面加载后会出现这种情况:
<div class="box-center">
<h1>Music 101</h1>
<div class="box-inner-center">
<ul>
<li>
<p>
<a href="http://***?attachment_id=150" rel="attachment wp-att-150">
<img class="alignnone wp-image-150" alt="Venice Symphony Orchestra" src="http://***/Venice-Symphony-Orchestra.jpg" width="960" height="640">
</a>
</p>
<p><span style="color: #000000;"><b><i>Some sample text.</i></b></span></p>
<p><span style="color: #000000;"><b>By Someone</b></span></p>
<p><span style="color: #000000;">Some quote and more content</span></p>
<p><span style="color: #000000;"><a href="http://***?p=141#more-141" class="more-link">(more…)</a></span></p>
</li>
</ul>
<a class="more" href="http://***/?cat=20">More Music 101 >></a>
</div>
</div>
我已尝试使用document.getElementById("box-center").childNodes
和document.getElementByTagName("img")
,然后for
循环显示结果并在其中设置属性,但上述行不会以某种方式返回任何结果。
如果可能,我宁愿不使用JQuery或任何其他库。
感谢您的时间。
答案 0 :(得分:2)
这假设你要调整第一次出现的&lt; img&gt;带有'box-inner-center'类的内部元素
var thebox = document.getElementsByClassName('box-inner-center')[0];
var theimg = thebox.getElementsByTagName('img')[0];
theimg.style.width = '100px';
答案 1 :(得分:2)
我没有看到任何你不能使用CSS的原因。我会建议这样的事情:
.box-center .box-inner-center img {
width:150px; /* or whatever */
height:auto; /* overrides the set HTML height*/
}
这将覆盖图像本身的宽度和高度属性,如有必要,您甚至可以更具体:.box-center .box-inner-center ul p > a img
或任何您想要的。