Как передвигать картинку в html
Перейти к содержимому

Как передвигать картинку в html

  • автор:

Как двигать картинку в html

Аватар пользователя Aleksey

Для движения изображения в HTML можно использовать свойство CSS "position". Например, чтобы переместить изображение вправо на 20 пикселей, можно использовать следующий код:

В данном примере мы задаем свойство "position" со значением "relative", что позволяет перемещать элемент относительно его начального положения. Затем мы используем свойство "left" со значением "20px", чтобы переместить изображение вправо на 20 пикселей.

Также можно использовать свойство "top" для перемещения изображения вверх или "bottom" для перемещения вниз.

Для анимации рекомендуется использовать свойство transform со значениями translate . Такой подход является более оптимизированным и затрачивает меньше ресурсов, а сама анимация будет выглядеть более плавной.

Например, здесь изображения логотипа будет смещено вправо на величину 100px .

Как передвигать картинку в html

You can easily move images in HTML using <marquee> tag. It is used to create scrolling images either from horizontally left to right or right to left, or vertically top to bottom or bottom to top. By default, image found within the <marquee> tag will scroll from right to left.

Syntax:

Attributes of <marquee> tag:

  • direction: Sets the direction for the scrolling images. The value of this attribute can be left, right, up or down.
  • behavior: The behavior tells about how the text scrolls. It can be one of the following values which are alternate, scroll, slide.

Example 1: The following example uses scroll behavior.

Перемещаем изображение по странице

Многие знают из программистов, а уж тем более из сайтостроителей, то для чего применяется CSS. Естественно основная его задача это отделение контента от дизайна. Но не будем углубляться в теорию, а посмотрим на это с другой стороны. А именно с той, как можно использовать CSS в паре с JavaScript. Мы по ходу данной статьи разберем пример того, как можно перемещать изображение прямо на странице. Но не все так просто, если брать во внимание кроссбраузерность (по крайней мере, с Internet Explorer и Opera). Вот Internet Explorer нам как раз и устроит сюрприз, но мы сделаем «финт ушами» и избавимся от него. Позже я расскажу, как в нашем случае обмануть Internet Explorer.

Для начала, создаем пустую html страницу. Сразу хочу отметить, что писать внешние скрипты и стили мы не будем, а будем все держать в одном месте. Хотя с профессиональной точки зрения это не правильно. И так создаем два стиля: один класс и один ID.

Далее в любом месте на странице (я предпочитаю в конце) размещаем DIV блок (вернее два, один вложен в другой).
Код выглядит вот так:

Сразу хочу остановиться на моменте, почему мы не могли обойтись классом или одним ID, а потому что подругому пока не получается. Феномен. Ну а теперь осталось самое главное – это код на JavaScript. Открываем секцию

Сразу объявим две глобальные переменные:

Следующие две функции особо рассматривать не будем, просто напишите вот такой код:

Единственное что можно сказать, так это то, что первая функция переводит строку в число, а вторая вычисляет координаты курсора мыши. Далее остались функции, которые собственно и будут осуществлять показ, скрывать и перемещать изображение. Для того чтобы продолжать дальше, нам необходимо работать с DIV блоками. Первый блок у нас имеет идентификатор – screenshow, а второй – screenmoving. Чтобы нам эти блоки найти, мы воспользуемся функцией getElementById, которая и находит элемент по его идентификатору. Далее сразу после нахождения элементов, необходимо определить координаты курсора мыши (именно в тот момент, когда вы нажали на ссылку). В функции showscreen, screenmove и screendown передается всего один параметр – evt. Атрибут event – обязателен. Собственно благодаря ему мы и определяем координаты курсора. Ну вот и первая функция, которая и отвечает за первоначальный показ изображения.

Обратите внимание на то, что атрибуты стиля написаны заглавными буквами, это неспроста. По другому не выходит. Пришлось провести ряд экспериментов, но это уже другая история…

Далее идет функция, которая прячет DIV блоки и убирает их со страницы. Все довольно просто. Всего лишь в стилях двух блоков, атрибуту display присваивается значение none. И нашему флагу присваивается значение false.

Далее идет функция screendown, которая обрабатывает нажатие кнопки мыши. Все что в ней происходит, так это то, что вычисляются координаты курсора мыши и флагу присваивается значение true, с таким значением флаг означает, что кнопка мыши нажата и удерживается.

Далее идет функция screenup, которая обрабатывает событие при отпускании кнопки мыши.

Ну вот, практически и все, осталось только рассмотреть последнюю функцию, которая собственно и осуществляет само перемещение изображения.

Ну и последний шаг это вставить ссылку. В нашем случае это вот такой код:

Который в комментарии я думаю, не нуждается.
Теперь можете кликнуть по ссылке «демонстрация» и посмотреть что должно получиться в итоге.

Теперь из истории про обман IE

Дело в том, что можно было обойтись всего лишь одним блоком. Но в Internet Explorer такой способ не проходит. Так как получается, будто мы двигаем картинку. Но вот собственно мной был придуман следующий метод: создаем первый слой, на первом слое размещаем изображение, и на первом же слое размещаем второй слой, который по размеру делаем таким как и первый. Затем в качестве фона на втором слое устанавливаем несуществующую страницу формата html. В итоге он получается как бы прозрачным. Если фон не задавать вообще, то IE опять же не позволит двигать картинку. А если фон сделать какого нибудь цвета, то мы естественно не увидим самой картинки. Демо версию скачать можно здесь.

CSS POSITION PROPERTY

Doganaker

In this article we are going to talk about CSS position property. This property basically helps you adjust the positioning of an element, making it a little bit easier to design your page. The position property has five different values: Static, absolute, fixed, relative and sticky. When you set position to one of these values you can manipulate the element’s position with the “top”, “bottom”, “right” and “left” properties.

STATIC

Let’s start with the default value of the position property which is “static”. There is not much to talk about this value. Static value is a default value for almost all elements and sets the elements according to the normal flow of the page. Elements with static position are not affected by the top,bottom,left and right properties. So there is not much use of this value unless you need to remove some positioning that got applied to an element out of your control.

Let’s have a div element added to our page.

Then let’s look at the class we assigned to the div element.

The display of these code blocks will be as…

As you can see the box positioned normally and we did not assigned a value for its position, for the reason static is a default value and elements positioned originally according to this value.

RELATIVE

Relative position value is the most confusing among others. So let’s start with what will happen when you set “position: relative”. Well if you just set position to relative and do not change the top, bottom, left and right properties, it will do the same thing as “position: static”. The element will be added according to the normal flow of the page. However, if you do change one of the positioning properties, the element will shift the amount you entered from where it would be originally. An example may make this more clear.

So here we will add another div element with different color.

And the CSS code of the box2 class.

And this is the outcome…

Here our second div element is set as its position is relative, since we have not given any positioning property. (Originally you would get two boxes one under the other, but I put these two div elements in an inclusive div element which has a display property set to flex.)

Now let’s see what will happen when we give top property. All we have to do is to add a top property to our box2 class.

As you can see the red box shifted down by 100px. The red box moved down by 100px relative to it self. When you use relative on an element and give a positioning property the element will change its position relative to its original position.

ABSOLUTE

This one is a bit different then others, however if you can use right it will be a powerful tool at disposal. Now, let me first explain why this value is different then others. Absolute is different then other values because elements with position set to it are removed from the flow of the page. This means that these elements do not affect other elements as well as other elements affect them. But also elements with absolute positioning are relative to the next parent element if there is. Otherwise they are relative to the page itself.

Let’s move on with another example. We are going to add a third box and it will be without a parent element.

Now let’s set the CSS code.

Now we get a black box on top of a blue box, however it is not because the blue box is the parent of the black box it is because since we have not given a parent element the third box is positioned relative to the page itself. Now remember the blue box has the static position and positioned accordingly. Same thing for the black box but the only difference is that the black box is positioned absolute.

Now let’s see what happens when we give some top and left property. CSS is below.

Now we did the same thing as we did with the element position set to relative. We gave some top and left property to position the box as we desire. The box moved itself relative to the page. We can place this box anywhere on the page in the location we want it to, however we should be careful while doing this because we can also limit the flexibility of our page if we ever overuse it.

This is absolute positioning, however I would like to show you this also with a parent element.

CSS code is the same.

Now let’s see what we got…

Well now the third box is on top of the second box and this is because the third one is positioned relative to the second. As I told before the second box is the parent of the third, so when positioned the third box is positioned relative to the second.

If you want you can also manipulate the third box. CSS is below.

What we got here is…

FIXED

Fixed value is similar to the absolute, this one is also removed from the flow and can be positioned anywhere on the page relative to the page itself. The small difference is that this element is fixed to the page, which means that if you scroll down it will also come down with you, it stays right at the position. This is used for navigation bars mostly, when you scroll down the page and the menu of the page also comes down with you.

Now I can’t really show a fixed element in this article but I trust that you will try it on your own, don’t worry I’ll provide the code.

This is what you should get as an outcome and if you add some more elements to the page so you can scroll down, you will see that the green box is fixed.

STICKY

Elements with a position set to sticky acts as both relative and fixed. Meaning that until a specified point this element will act as relative positioned element but when it reaches that specified point it will act as a fixed element.

Also the HTML code.

If you add some text to your page for scrolling (write “lorem*20”, then hit enter to have a long text), you will see that when you scroll down this box will reach its scroll position (top:0) and then fix itself to the page (sticks).

If you also apply this you should get this…

And after you scroll down you should get…

See, the box sticks to the position where we told it should stick.

This value is supported by latest versions of Firefox browsers and Safari browsers, also partially supported by Chrome and Opera. For more detailed information please check out the link below.

Can I use. Support tables for HTML5, CSS3, etc

"Can I use" provides up-to-date browser support tables for support of front-end web technologies on desktop and mobile…

Well, that is all for this article. We covered the most used position values in CSS to make your web designs a bit less challenging. CSS may seem hard but once you get to it and try a lot you start to learn how to use it, as I learned more about the position property while writing this article…

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *