1

我正在从 html 调用 javascript 函数。但它一直返回错误并说函数未在jsfiddle中定义。

这是html代码

<div id="Container">
    <img alt="Click to zoom" class="image" onclick="resizeImg(this)" 
src="http://www.extremetech.com/wp-content/uploads/2012/12/Audi-A1.jpg" />
</div>

这是javascript

function resizeImg (img) {
        var resize = 150; // resize amount in percentage
        var origH  = 61;  // original image height
        var origW  = 250; // original image width
        var mouseX = event.x;
        var mouseY = event.y;
        var newH   = origH * (resize / 100);
        var newW   = origW * (resize / 100);

        // Set the new width and height
        img.style.height = newH;
        img.style.width  = newW;

        var c = img.parentNode;

        // Work out the new center
        c.scrollLeft = (mouseX * (resize / 100)) - (newW / 2) / 2;
        c.scrollTop  = (mouseY * (resize / 100)) - (newH / 2) / 2;
    }

为什么以及如何解决它?

4

2 回答 2

4

您需要no-wrap in body/head在左侧面板的第二个下拉菜单中进行选择。

由于您选择了 onDomReady,因此您的脚本被$(function(){...}) ex包围

<script type="text/javascript">//<![CDATA[ 
$(function(){
function resizeImg (img) {
    var resize = 150; // resize amount in percentage
    var origH  = 61;  // original image height
    var origW  = 250; // original image width
    var mouseX = event.x;
    var mouseY = event.y;
    var newH   = origH * (resize / 100);
    var newW   = origW * (resize / 100);

    // Set the new width and height
    img.style.height = newH;
    img.style.width  = newW;

    var c = img.parentNode;

    // Work out the new center
    c.scrollLeft = (mouseX * (resize / 100)) - (newW / 2) / 2;
    c.scrollTop  = (mouseY * (resize / 100)) - (newH / 2) / 2;
}

});//]]>  

</script>

这使得函数resizeImg对传递给的匿名函数是本地的$(),因此它对全局范围不可见。单击图像时,将在全局范围内搜索该方法,该方法不可见,这是错误的原因

于 2013-08-14T18:11:07.033 回答
1

您没有在新的高度和宽度中指定“px”,在 jsfiddle 中您必须将其包装在 head 部分

function resizeImg (img) {
    var resize = 150; // resize amount in percentage
    var origH  = 61;  // original image height
    var origW  = 250; // original image width
    var mouseX = event.x;
    var mouseY = event.y;
    var newH   = origH * (resize / 100);
    var newW   = origW * (resize / 100);

    // Set the new width and height
    img.style.height = newH+"px";   // changes made
    img.style.width  = newW+"px";

    var c = img.parentNode;

    // Work out the new center
    c.scrollLeft = (mouseX * (resize / 100)) - (newW / 2) / 2;
    c.scrollTop  = (mouseY * (resize / 100)) - (newH / 2) / 2;
}

工作 jsfiddle演示

希望这有帮助 谢谢

于 2013-08-14T18:20:16.447 回答