Форум программистов, компьютерный форум, киберфорум
JavaScript для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.88/8: Рейтинг темы: голосов - 8, средняя оценка - 4.88
0 / 0 / 3
Регистрация: 30.05.2016
Сообщений: 171

Исправить ошибку в добавлении размеров в border-radius

07.02.2019, 20:26. Показов 1625. Ответов 3
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Есть css генератор
http://messer-84.github.io/too... sGenerator
хочу сделать по аналогии, но в логике добавлении размеров в бордер-радиус ошибка
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<style>
span {
    margin-right: 15px;
}
div#gen-info {
    width: 350px;
    height: 100px;
    background: yellow;
    margin: 30px;
}
div#gen-result {
    background: green;
    width: 300px;
    height: 300px;
    margin: 30px;
}
.blocks{
    display: flex;
}
.inside {
    text-align: center;
    width: 50px;
    height: 50px;
    float: left;
    padding: 50px;
    vertical-align: middle;
    line-height: 50px;
}
 
</style>
 
<body>
    <h1>Border radius generator</h1>
    <div class="windOfChange">
        <div><span>Верхний левый угол:</span>
            <span><input type="range" name="rangeBR" class="top-left" id="borderTopLeftRadius" min="0" max="150" step="1" value="0"></span>
            <span><input type="text" name="dataBR" id="dataTopLeft" class="top-left" ></span>
        </div>
        <div>
            <span>Верхний правый угол:</span>
            <span><input type="range" name="rangeBR" class="top-right" id="borderTopRightRadius" min="0" max="150" step="1"></span>
            <span><input type="text" name="dataBR" id="dataTopRight" class="top-right" ></span>
        </div>
        <div>
            <span>Нижний правый угол:</span>
            <span><input type="range" name="rangeBR" class="bottom-right" id="borderBottomRightRadius" min="0" max="150" step="1"></span>
            <span></span><input type="text" name="dataBR" id="dataBottomRight" class="bottom-right" >
        </div>
        <div>
            <span>Нижний левый угол:</span>
            <span><input type="range" name="rangeBR" class="bottom-left" id="borderBottomLeftRadius" min="0" max="150" step="1"></span>
            <span></span><input type="text" name="dataBR" id="dataBottomLeft" class="bottom-left" >
        </div>
 
    </div>
    <div class="blocks">
        <div id="gen-result">
            <div class="inside top-left">1</div>
            <div class="inside top-right">1</div>
            <div class="inside bottom-left">1</div>
            <div class="inside bottom-right">1</div>
        </div>
        <div id="gen-info">
            <p></p>
        </div>
    </div>
 
</body>
 
</html>
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
let windOfChange = document.querySelector('.windOfChange');
let genResult = document.getElementById('gen-result');
let borderTopLeftRadius = document.getElementById('borderTopLeftRadius').value;
let dataTopLeft = document.getElementById('dataTopLeft').value;
let borderTopRightRadius = document.getElementById('borderTopRightRadius').value;
let dataTopRight = document.getElementById('dataTopRight').value;
let borderBottomRightRadius = document.getElementById('borderBottomRightRadius').value;
let dataBottomRight = document.getElementById('dataBottomRight').value;
let borderBottomLeftRadius = document.getElementById('borderBottomLeftRadius').value;
let dataBottomLeft = document.getElementById('dataBottomLeft').value;
 
windOfChange.addEventListener('input', e => {
//  размеры округления бордера
    let topLeft;
    let topRight;
    let bottomLeft;
    let bottomRight;
 
// найти элемент по класу на котором произошло событие
 
    let myClass = document.querySelectorAll(`.${e.target.className}`);
 
    e.target.id === 'borderTopLeftRadius' || 'dataTopLeft' ? topLeft = ` ${e.target.value}px ` :
    e.target.id === 'borderTopRightRadius' || 'dataTopRight' ? topRight = ` ${e.target.value}px ` :
    e.target.id === 'borderBottomRightRadius' || 'dataBottomRight' ? bottomLeft = ` ${e.target.value}px ` :
    e.target.id === 'dataBottomLeft' || 'dataBottomLeft' ? bottomRight = ` ${e.target.value}px ` : '';
 
// здесь добавляю размеры
 
    genResult.style.borderRadius = topLeft + topRight + bottomRight + bottomLeft; 
 
// если событие произошло на текстовом поле то значение поля будет равно значению ползунка
 
    e.inputType === 'insertText' ? myClass[0].value = myClass[1].value : myClass[1].value = myClass[0].value;
 
    console.log(topLeft);
    console.log(topRight);
    console.log(bottomLeft);
    console.log(bottomRight);
 
 
})
Добавлено через 41 минуту
Дико извиняюсь, помучился и сделал сам, может только чище сделать, переменные topLeft, topRight,
bottomLeft, bottomRight, в ифах торчат их бы вынести в глобальную видимость но чтобы значения я мог в ифах словить
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
let windOfChange = document.querySelector('.windOfChange');
let genResult = document.getElementById('gen-result');
let borderTopLeftRadius = document.getElementById('borderTopLeftRadius').value;
let borderTopRightRadius = document.getElementById('borderTopRightRadius').value;
let borderBottomRightRadius = document.getElementById('borderBottomRightRadius').value;
let borderBottomLeftRadius = document.getElementById('borderBottomLeftRadius').value;
 
let topLeft;
let topRight;
let bottomLeft;
let bottomRight;
 
windOfChange.addEventListener('input', e => {
 
    let myClass = document.querySelectorAll(`.${e.target.className}`);
    e.inputType === 'insertText' ? myClass[0].value = myClass[1].value : myClass[1].value = myClass[0].value;
    if (e.target.id === 'borderTopLeftRadius' || 'dataTopLeft') {
        let dataTopLeft = document.getElementById('dataTopLeft').value;
          topLeft = ` ${dataTopLeft}px `;
          genResult.style.borderTopLeftRadius = topLeft;
    }
    if (e.target.id === 'borderTopRightRadius' || 'dataTopRight') {
        let dataTopRight = document.getElementById('dataTopRight').value;
         topRight = ` ${dataTopRight}px `;
         genResult.style.borderTopRightRadius = topRight;
 
    } if (e.target.id === 'borderBottomRightRadius' || 'dataBottomRight') {
        let dataBottomRight = document.getElementById('dataBottomRight').value;
         bottomLeft = ` ${dataBottomRight}px `;
         genResult.style.borderBottomRightRadius = bottomLeft;
 
    } if (e.target.id === 'borderBottomLeftRadius' || 'dataBottomLeft') {
        let dataBottomLeft = document.getElementById('dataBottomLeft').value;
         bottomRight = ` ${dataBottomLeft}px `;
         genResult.style.borderBottomLeftRadius = bottomRight;
        
    }
    genResult.style.borderRadius = topLeft + topRight + bottomRight + bottomLeft;
 
})
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
07.02.2019, 20:26
Ответы с готовыми решениями:

Css border-bottom-right-radius в javascript
Как изменять радиус углов примеру тега DIV Если менять углы DIV все вместе получается: IDef.style.borderRadius= '6px'; ...

Некорректная работа свойств border и border-radius на мобильных устройствах
Доброго времени суток, произошла интересная вещь: использовала border-radius:50% и border:6px solid white на картинку в браузере...

border-radius в IE
как сделать border-radius и box-shadow в IE???

3
Эксперт JSЭксперт HTML/CSS
2151 / 1496 / 651
Регистрация: 16.04.2016
Сообщений: 3,696
08.02.2019, 00:46
Лучший ответ Сообщение было отмечено Спрашыватель как решение

Решение

Оставлю здесь, просто как вариант - https://codepen.io/qwerty_wasd/pen/mvpreW
HTML5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<div class="module-generator-border">
  <h1>Border radius generator</h1>
  <div class="wrapper-data-interface">
    <div class="name-range-item"><span>Верхний левый угол:</span><span>Верхний правый угол:</span><span>Нижний правый угол:</span><span>Нижний левый угол:</span></div>
    <div class="range-item">
      <input type="range" min="0" max="200" step="1" value="0"/>
      <input type="range" min="0" max="200" step="1" value="0"/>
      <input type="range" min="0" max="200" step="1" value="0"/>
      <input type="range" min="0" max="200" step="1" value="0"/>
    </div>
    <div class="view-range">
      <input type="number" min="0" max="200" step="1" value="0"/>
      <input type="number" min="0" max="200" step="1" value="0"/>
      <input type="number" min="0" max="200" step="1" value="0"/>
      <input type="number" min="0" max="200" step="1" value="0"/>
    </div>
  </div>
  <div class="block-bordered">
    <div class="corner">0px</div>
    <div class="corner">0px</div>
    <div class="corner">0px</div>
    <div class="corner">0px</div>
    <div class="center">border-radius: 0px 0px 0px 0px;</div>
  </div>
</div>
CSS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
*,
*:after,
*:before {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  -webkit-tap-highlight-color: transparent;
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  outline: 0;
}
 
/*стили выше добавлены только для этого примера, в реальном проекте используйте normalize.css\reset.css*/
.module-generator-border h1 {
  text-align: center;
}
.module-generator-border .wrapper-data-interface {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
}
.module-generator-border .wrapper-data-interface .name-range-item,
.module-generator-border .wrapper-data-interface .range-item,
.module-generator-border .wrapper-data-interface .view-range {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  margin: 0 10px;
}
.module-generator-border .wrapper-data-interface span,
.module-generator-border .wrapper-data-interface input {
  margin: 5px 0;
}
.module-generator-border .block-bordered {
  position: relative;
  height: 400px;
  width: 400px;
  background: green;
  margin: 15px auto;
  font-weight: bold;
  color: white;
}
.module-generator-border .block-bordered .corner {
  position: absolute;
  -webkit-transform: translate(-20%, -20%);
          transform: translate(-20%, -20%);
}
.module-generator-border .block-bordered .corner:first-child {
  top: 20%;
  left: 20%;
}
.module-generator-border .block-bordered .corner:nth-child(2) {
  top: 20%;
  right: 20%;
}
.module-generator-border .block-bordered .corner:nth-child(3) {
  bottom: 20%;
  right: 20%;
}
.module-generator-border .block-bordered .corner:nth-child(4) {
  bottom: 20%;
  left: 20%;
}
.module-generator-border .block-bordered .center {
  -webkit-user-select: text;
  -moz-user-select: text;
  -ms-user-select: text;
  user-select: text;
  -webkit-tap-highlight-color: #186ca1;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
          transform: translate(-50%, -50%);
  white-space: nowrap;
  cursor: text;
}
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
let opBGener = {
  module: document.querySelector(`.module-generator-border`),
  iRange: [...document.querySelectorAll(`.module-generator-border .range-item > input`)],
  iView: [...document.querySelectorAll(`.module-generator-border .view-range > input`)],
  bCorner: [...document.querySelectorAll(`.module-generator-border .block-bordered > .corner`)],
  bCenter: document.querySelector(`.module-generator-border .block-bordered > .center`),
  events: {
    input: e => opBGener.iRange.includes(e.target) || opBGener.iView.includes(e.target) ?
    ((opBGener.iRange.includes(e.target) ? opBGener.iView : opBGener.iRange)[(opBGener.iRange.includes(e.target) ? opBGener.iRange : opBGener.iView).indexOf(e.target)].value = e.target.value,
     opBGener.bCorner[(opBGener.iRange.includes(e.target) ? opBGener.iRange : opBGener.iView).indexOf(e.target)].textContent = `${e.target.value}px`,
     opBGener.bCenter.textContent = `border-radius: ${(opBGener.iRange.includes(e.target) ? opBGener.iRange : opBGener.iView)[0].value}px ${(opBGener.iRange.includes(e.target) ? opBGener.iRange : opBGener.iView)[1].value}px ${(opBGener.iRange.includes(e.target) ? opBGener.iRange : opBGener.iView)[2].value}px ${(opBGener.iRange.includes(e.target) ? opBGener.iRange : opBGener.iView)[3].value}px;`,
    opBGener.module.children[2].style.borderTopLeftRadius = `${(opBGener.iRange.includes(e.target) ? opBGener.iRange : opBGener.iView)[0].value}px`,
    opBGener.module.children[2].style.borderTopRightRadius = `${(opBGener.iRange.includes(e.target) ? opBGener.iRange : opBGener.iView)[1].value}px`,
    opBGener.module.children[2].style.borderBottomRightRadius = `${(opBGener.iRange.includes(e.target) ? opBGener.iRange : opBGener.iView)[2].value}px`,
    opBGener.module.children[2].style.borderBottomLeftRadius = `${(opBGener.iRange.includes(e.target) ? opBGener.iRange : opBGener.iView)[3].value}px`) : false
  }
}
opBGener.module.addEventListener(`input`, opBGener.events.input);
window.addEventListener(`beforeunload`, () => {
  opBGener.module.removeEventListener(`input`, opBGener.events.input);
  opBGener = undefined;
});
0
0 / 0 / 3
Регистрация: 30.05.2016
Сообщений: 171
08.02.2019, 10:30  [ТС]
Qwerty_Wasd, Мда... почуствовал себя тупым, а так решение интересное, очень структурировано, вроде бы и понял, но так же не смог бы, наверное у тебя опыта по меньшей мере года 4, спасибо за решение
0
Эксперт JSЭксперт HTML/CSS
2151 / 1496 / 651
Регистрация: 16.04.2016
Сообщений: 3,696
08.02.2019, 11:54
Спрашыватель,
Цитата Сообщение от Спрашыватель Посмотреть сообщение
почуствовал себя тупым
ну блиин)) Я ж не для этого сюда его выложил Написал же - как вариант Не надо себя таким считать, двигайтесь вперед
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
08.02.2019, 11:54
Помогаю со студенческими работами здесь

border-radius и IE
Вот мой CSS-код: -moz-border-radius: 7px; -webkit-border-radius: 7px; -khtml-border-radius: 7px; border-radius: 7px; behavior:...

Достопочтенный IE и border-radius
Здравствуйте. Есть страница http://alizamoney.myjino.ru/pages/login.html Попробуйте открыть ее в хроме и в IE. Я не могу понять почему...

border-radius В ie8
Вот собственно, надо подружить border-radius и IE 8. Нашел в инте PIE css3 прочитал документацию, вроде все сделал по инструкции, но вместо...

Не работает border-radius
&lt;table style=&quot;border-radius:10px;&quot; &gt; &lt;tr&gt;&lt;td&gt;&lt;big&gt;&lt;big&gt;&lt;center&gt;text&lt;/center&gt;&lt;/td&gt;&lt;/tr&gt; ...

Border-radius останавливается
Подскажите, пожалуйста, есть картинка квадратная, хочу ее обрезать до круга, использую border-radisus - обрезается чуть-чуть и дальше...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит переходные токи и напряжения на элементах схемы. . . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru