我正在测试使用 javascript 调整图像大小。我正在使用Flask,我的htlm代码如下:
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %} - Home{% endblock %}
{% block page_content %}
<div class="page-header">
<h1> Rubbish bags collected since 2016 </h1>
</div>
<div>
<img id="rubbish" src="{{ url_for('.fig') }}" alt="Rubbish bags">
</div>
<p>Click the button to get the ID of the image.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
{% endblock %}
{% block scripts %}
{{ super() }}
{% endblock %}
该图像由Flask 视图函数生成。用于检查图像 ID的函数“myFunction()”如下:
function myFunction() {
var x = document.getElementById('rubbish').id;
document.getElementById('demo').innerHTML = x;
}
当我点击“ myFunction() ”时,ID图像的结果是“垃圾”,正如预期的那样。但是,当我尝试通过更改窗口大小来访问图像以更改with属性时,没有任何反应。这是javascript代码:
$(function() {
if($(window).width() < 500)
var parentwith = $('rubbish').parent().css('width');
$('rubbish').css('width', parentwith);
});
任何想法 ?
if($(window).width() < 500)
var parentwith = $('rubbish').parent().css('width'); // Should be $('#rubbish')
// If window's width is >= 500, here you'll get a "parentwith is undefined" error
$('rubbish').css('width', parentwith);
但是为什么要将 Javascript ( document.getElementById('rubbish')
) 和 jQuery ( $("#rubbish")
) 混合在一起呢?
...但是,为什么要这样做,只是为了将图像的宽度设置为其父级的宽度?一个简单的 CSS 媒体查询做同样的事情并且执行速度更快:
@media (max-width: 500px){
img#rubbish {
width : 100%;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句