이미지 크기 조정 및 확대/축소
-
20-12-2019 - |
문제
나는 보았다 이 질문 도움이 되었지만 확대/축소 버튼을 적용하는 코드로 더 많은 작업을 시도했지만 제대로 작동하지 않는 것 같습니다.저는 javascript와 jquery를 처음 접했고 "this" 키워드가 어떻게 적용되는지 이해하는 데 어려움을 겪고 있습니다.
$('#plus').click(
function( event ){
var scale = 150/100;
var pos = $('#Container img').offset();
var clickX = event.pageX - pos.left;
var clickY = event.pageY - pos.top;
var container = $('#Container img').parent().get(0);
$('#Container img').css({
width: this.width*scale,
height: this.height*scale
});
container.scrollLeft = ($(container).width() / -2 ) + clickX * scale;
container.scrollTop = ($(container).height() / -2 ) + clickY * scale;
}
);
$('#minus').click(
function( event ){
var scale = 100/150;
var pos = $('#Container img').offset();
var clickX = event.pageX - pos.left;
var clickY = event.pageY - pos.top;
var container = $('#Container img').parent().get(0);
$('#Container img').css({
width: this.width*scale,
height: this.height*scale
});
container.scrollLeft = ($(container).width() / -2 ) + clickX * scale;
container.scrollTop = ($(container).height() / -2 ) + clickY * scale;
}
);
나는 만들었습니다 jsfiddle 내 코드를 데모합니다.
해결책
this
클릭한 요소를 나타냅니다(실제로는 $(this)
jQuery에서는) 클릭 후에 호출되는 함수가 해당 범위를 갖기 때문입니다.따라서 귀하의 예에서는 this
플러스 또는 마이너스 버튼을 참조하므로 기술적으로 크기가 조정됩니다. 그들의 너비/높이를 선택하고 결과 너비/높이를 이미지에 적용합니다.
디버그할 필요를 피하는 일반적인 방법 this
표현은 함수의 맨 위에 있는 변수에 이를 할당하는 것입니다. 예를 들면 다음과 같습니다.
var self = this;
또는
var $myClickedButton = this;
또한 스타일링에 주의하세요.
element.width
요소의 너비 속성을 나타냅니다(예:<img width="300" />
, jQuery와 유사$(element).attr('width')
), 하지만element.style.width
CSS 너비를 나타냅니다(예:<img style="width: 300px;" />
, 또는<img class="myClassWithDenotedWidth" />
, jQuery와 유사$(element).css('width')
).후자에도 단위가 있으므로 숫자 값만 얻으려면 이를 parsInt해야 합니다.
플러스 버튼에 대해 문제를 해결했습니다. 마이너스에도 동일한 원리를 따를 수 있습니다.내가 한 일은 다음과 같습니다.
var $image = $('#Container img');
var container = $image.parent().get(0);
$('#Container img').css({
width: Math.round(parseInt($image.css('width'), 10) * scale),
height: Math.round(parseInt($image.css('height'), 10) * scale)
});
여기에서 확인하세요: http://jsfiddle.net/shomz/4A9Gt/4/ (확대/축소가 덜 고르게 되도록 CSS 전환도 추가했습니다)
제휴하지 않습니다 StackOverflow