按比例调整我在运行前无法访问的图像的大小

Resizing an image proportionally that I don't have access to before runtime

本文关键字:访问 图像 调整 运行 按比例      更新时间:2023-09-26

我一整天都在寻找解决方案,并阅读了许多关于图像调整大小和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 &gt;&gt;</a>
        </div>
    </div>

我尝试使用document.getElementById("box-center").childNodesdocument.getElementByTagName("img"),然后使用for循环通过结果并设置属性,但上面的行不知何故没有返回结果。

我宁愿不使用JQuery或任何额外的库,如果可能的话。

感谢您的宝贵时间。

我不明白为什么你不能使用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或任何你想要的。

这里假设您想要调整class 'box-inner-center'的内部元素

var thebox = document.getElementsByClassName('box-inner-center')[0];
var theimg = thebox.getElementsByTagName('img')[0];
theimg.style.width = '100px';